问题
Compare Array of Objects
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"}])
I am having a disconnect with looping arrays of objects with different lengths and properties. I have tried looping and IndexOf but due to different lengths, I cannot compare the two arrays that way. I feel like a filter might be a good tool but have had no luck. Any thoughts?
回答1:
Create a Set of properties from the 1st array (the keys), and then Array#filter the 2nd array (the values) using the set:
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);
来源:https://stackoverflow.com/questions/46713350/compare-array-of-objects