JavaScript merging objects by id

前端 未结 16 2022
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 09:43

What\'s the correct way to merge two arrays in Javascript?

I\'ve got two arrays (for example):

var a1 = [{ id : 1, name : \"test\"}, { id : 2, name :         


        
16条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 10:49

    Wanted to add this answer which is derived from @daisihi answer above. Main difference is that this uses the spread operator. Also, at the end I remove the id because it was not desirable in the first place.

    const a3 = [...a1, ...a2].reduce((acc, x) => {
       acc[x.id] = {...acc[x.id] || {}, ...x};
       return acc;
    }, {});
    

    This part was taken from another post. removing a property from a list of objects in an array

    const newArray = Object.values(a3).map(({id, ...keepAttrs}) => keepAttrs);
    

提交回复
热议问题