Home > front end >  How to return a new array of objects that contains merged data from source and target?
How to return a new array of objects that contains merged data from source and target?

Time:08-19

I want to compare an oldItems array of objects and if id matches the id in my updatedItems array of objects, I want to update the object, copying over the property from oldItems if there is no value in updatedItems for that key or if that property is not defined, and replacing the oldItems object property with the updatedItems object property if there IS a value. I want to store all the changes in a result variable and log result to the console. The result variable should contain exactly an object with id: 1, the new sandwich name, and the old price, as well as id: 2 with the new price and the new name.

const oldItems = [
    {
        id: 0,
        name: "peanut butter sandwich",
        price: 3
    },
    {
        id: 1,
        name: "cheese sandwich",
        price: 4
    }, 
    {
        id: 2,
        name: "chicken sandwich",
        price: 6
    }
]

const updatedItems = 
    [{
        id: 1,
        name: "grilled cheese sandwich"
    }, {
        id: 2,
        price: 5,
        name: "chicken and waffles sandwich"
    }]

I tried:

let result = oldItems.map((item, i) => Object.assign({}, item, updatedItems[i]));  
console.log(result);

CodePudding user response:

I'm not completely certain of your use-case, but this will produce the result you describe.

oldItems.map(o => {
    const update = updatedItems.find(u => u.id === o.id);
    if (update) return {
        ...o,
        ...update
    }

}).filter(x => x)

result :

[
  { id: 1, name: 'grilled cheese sandwich', price: 4 },    
  { id: 2, name: 'chicken and waffles sandwich', price: 5 }
]

CodePudding user response:

First, your code maps over the wrong array, you should be mapping updatedItems.

Second, you can't use the same i for both arrays, since the items with the same id are not at the same indexes. Use find() to search the array for the id.

In ES6 you can use ... to merge objects instead of Object.assign().

const oldItems = [{
    id: 0,
    name: "peanut butter sandwich",
    price: 3
  },
  {
    id: 1,
    name: "cheese sandwich",
    price: 4
  },
  {
    id: 2,
    name: "chicken sandwich",
    price: 6
  }
];

const updatedItems = [{
  id: 1,
  name: "grilled cheese sandwich"
}, {
  id: 2,
  price: 5,
  name: "chicken and waffles sandwich"
}];

let result = updatedItems.map((item) => ({
  ...oldItems.find(el => el.id == item.id),
  ...item
}));
console.log(result);

CodePudding user response:

you can use spread opearator.

const newArray = [...oldItems, ...updatedItems];
  • Related