gpt4 book ai didi

javascript - 如何合并对象数组但在 JavaScript 中取消移位数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:36:40 25 4
gpt4 key购买 nike

我想合并这两个对象数组,但对于 urls 我想使用 unshift 来合并数组而不是替换。

举个例子

var arr1 = [{
"keyword": "name",
"score": 0.8992112752974006,
"urls": ["url1"],
"ids": ["5748bf9ab58adb2f614da195"]
}, {
"keyword": "name1",
"score": 0.39953909596222775,
"urls": ["url2"],
"ids": ["5743260055f979a31fa98971"]
}, {
"keyword": "name3",
"score": 0.4960953181766197,
"urls": ["url4"],
"ids": ["58c04cd5208b4945c3920cad"]
}, {
"keyword": "name4",
"score": 0.3337163443410707,
"urls": ["url5"],
"ids": ["573628c38e32eeb039377f7e"]
}];

var arr2 = [{
"keyword": "name",
"score": 0.8992112752974006,
"urls": ["url6"],
"ids": [""]
}, {
"keyword": "name1",
"score": 0.39953909596222775,
"urls": ["url7"],
"ids": [""]
}]

我想要的结果是

[{
"keyword": "name",
"score": 0.8992112752974006,
"urls": ["url6", "url1"],
"ids": ["5748bf9ab58adb2f614da195"]
}, {
"keyword": "name1",
"score": 0.39953909596222775,
"urls": ["url7", "url2"],
"ids": ["5743260055f979a31fa98971"]
}, {
"keyword": "name3",
"score": 0.4960953181766197,
"urls": ["url4"],
"ids": ["58c04cd5208b4945c3920cad"]
}, {
"keyword": "name4",
"score": 0.3337163443410707,
"urls": ["url5"],
"ids": ["573628c38e32eeb039377f7e"]
}];

这是我的尝试,但结果会替换 url 数组;

var a3 = arr1.concat(arr2).reduce((acc, x) => {
acc[x.keyword] = Object.assign(acc[x.keyword] || {}, x);
return acc;
}, {});
console.log(a3);

它将只是 urls 将被合并。其他值将被覆盖。

最佳答案

你可以使用 Map用于收集具有相同 keyword 的对象并在必要时进行更新。此解决方案适用于任意数量的数组。

var array1 = [{ keyword: "name", score: 0.8992112752974006, urls: ["url1"], ids: ["5748bf9ab58adb2f614da195"] }, { keyword: "name1", score: 0.39953909596222775, urls: ["url2"], ids: ["5743260055f979a31fa98971"] }, { keyword: "name3", score: 0.4960953181766197, urls: ["url4"], ids: ["58c04cd5208b4945c3920cad"] }, { keyword: "name4", score: 0.3337163443410707, urls: ["url5"], ids: ["573628c38e32eeb039377f7e"] }],
array2 = [{ keyword: "name", score: 0.8992112752974006, urls: ["url6"], ids: [""] }, { keyword: "name1", score: 0.39953909596222775, urls: ["url7"], ids: [""] }],
map = new Map,
result = [],
fn = a => {
if (map.has(a.keyword)) {
map.get(a.keyword).urls.unshift(...a.urls);
return;
}
map.set(a.keyword, a);
result.push(a);
};

[array1, array2].forEach(a => a.forEach(fn));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何合并对象数组但在 JavaScript 中取消移位数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46205753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com