I am trying to override item and add new item/object in given array of objects .
here is my code
const replaceOrAdd = (sourceArray, overrideArray, key = "name") => {
const existingIndex = sourceArray.findIndex(
(item) => item[key] === overrideArray[key]
);
if (existingIndex >= 0) {
sourceArray[existingIndex] = overrideArray;
} else {
sourceArray.push(overrideArray);
}
return sourceArray;
};
const source = [
{
label: "WORK_ORDER_NUMBER",
name: "job_order_number",
visible: true,
},
{
label: "WORK_ORDER_VALIDITY_DATE",
name: "validity_date",
visible: true,
},
{
label: "BOOKING_ID",
name: "booking_number",
visible: true,
},
{
label: "BOOKING_TYPE",
name: "booking_type",
rules: {},
visible: true,
},
];
const replace = [
{
label: "WORK_ORDER_NUMBER",
name: "job_order_number",
visible: false,
},
{
label: "BOOKING_ID",
name: "booking_number",
visible: false,
},
{
label: "XXXXX",
name: "XXXXXX",
visible: false,
},
];
replaceOrAdd(source, replace);
console.log(source);
Expected output :
[
{
label: "WORK_ORDER_NUMBER",
name: "job_order_number",
visible: false,
},
{
label: "WORK_ORDER_VALIDITY_DATE",
name: "validity_date",
visible: true,
},
{
label: "BOOKING_ID",
name: "booking_number",
visible: false,
},
{
label: "BOOKING_TYPE",
name: "booking_type",
rules: {},
visible: true,
},
{
label: "XXXXX",
name: "XXXXXX",
visible: false,
},
];
I am trying to override in the source array if "name" key match .. if they there is extra object in replace object . I am trying to add that object.
Here in example name: "job_order_number", , name: "booking_number", match .. I want to override this object and add this object name: "XXXXXX", as it is not found
2
Answers
Not sure why you will like to mutate the original array. You can use the
replaceOrAdd
to return a new array & inside this function you can create amap
from thesourceArray
then iterate over theoverrideArray
and add its value to themap
. If themap
has thekey
then it will override else it will add the value.The OP wants to mutate the original array, so iterate the replace array and find existing item with the same property value. If found, replace the item, otherwise push it: