gpt4 book ai didi

javascript - 比较对象数组

转载 作者:行者123 更新时间:2023-12-03 03:17:18 26 4
gpt4 key购买 nike

比较对象数组

 function compare (arr1, arr2){
//if object key value pair from arr2 exists in arr1 return modified array
for (let obj of arr2) {
if(obj.key === arr1.key){
return obj
}
}
}
// Should return [{key: 1, name : "Bob", {key: 2, name : "Bill"}]

compare([{key: 1}, {key: 2}],
[{key: 1, name : "Bob"}, {key: 3, name : "Joe"}, {key: 2, name : "Bill"}])

我与具有不同长度和属性的对象循环数组断开连接。我尝试过循环和 IndexOf 但由于长度不同,我无法以这种方式比较两个数组。我觉得过滤器可能是一个很好的工具,但没有运气。有什么想法吗?

最佳答案

创建 Set第一个数组(键)中的属性,然后 Array#filter使用集合的第二个数组(值):

function compareBy(prop, keys, values) {
const propsSet = new Set(keys.map((o) => o[prop]));

return values.filter((o) => propsSet.has(o[prop]));
}

const result = compareBy('key', [{key: 1}, {key: 2}],
[{key: 1, name : "Bob"}, {key: 3, name : "Joe"}, {key: 2, name : "Bill"}])

console.log(result);

关于javascript - 比较对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46713350/

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