【发布时间】:2022-11-24 20:17:16
【问题描述】:
我需要组合两个对象数组:
const local: [
{id: 1, balance: 2200, ref: 'A'},
{id: 2, balance: 2100, ref: 'C'}
]
const remote: [
{id: 1, balance: 3300, ref: 'B'},
]
我需要合并这些数组,这样任何两个具有相同 ID 的对象都会被合并 - 保持相同的 ID,保持 remote 的余额并合并它们的 ref 值,所以这个例子的理想输出是:
[
{ id: 1, balance: 3300, text: 'A / B' },
{ id: 2, balance: 2100, text: 'C' }
]
我该怎么做?我试过以下方法:
function mergeFunc(remoteArray, localArray) {
const newArray = [];
//loop over one of the arrays
for (const localObj of localArray) {
//for each iteration, search for object with matching id in other array
if(remoteArray.some(remoteObj => remoteObj.id === localObj.id)){
//if found matching id, fetch this other object
const id:matchingRemoteObj = remoteArray.find(item => item.id === localObj.id);
//create new, merged, object
const newObj = {id:matchingRemoteObj.id, balance: id:matchingRemoteObj.balance, text:`${localObj.text} / ${id:matchingRemoteObj.text}`}
//push new value to array
newArray.push(newObj);
}
}
return newArray;
}
问题是,此解决方案为我提供了一组具有匹配 ID 的合并对象。我需要一个数组全部对象,只合并具有匹配 id 的对象...
【问题讨论】:
-
remote可以拥有 ID 不在local中的对象吗?如果是这样,这些对象是否应该包含在输出中? -
@NickParsons 是的,远程和本地是独立的数组,偶尔需要“同步”并合并。合并后的输出应该包含来自两个数组的所有唯一对象,以及 id 匹配的合并对象......
标签: javascript arrays json object