问题
For example consider the following array with objects.
var collection = [{name:'user1',phone:'203'},
{name:'user2',phone:'5050'},
{name:'user1',phone:'203'}]
Now I want to compare the each object with each other and give the result as.
var newCollection = {name:'user1',phone:'203', rowMatch:'true'},
{name:'user2',phone:'5050', rowMatch:'false'},
{name:'user1',phone:'203',rowMatch:'true'}
So, I want the new collecition like this where it compares and updates with new property when object properties match like the first and third object.
回答1:
You can use newCollection or manipulate in the collection like this
collection.forEach((item)=>{
item.rowMatch = (collection.filter((e)=>{return (e.name==item.name&&e.phone==item.phone)}).length>1)?'true':'false';
})
console.log(collection)
Simple is that.Here is working JSFiddle for it https://jsfiddle.net/touqeer/pgdsw9Le/1/ .
回答2:
var newCollection = collection.map(item => {
item.rowMatch = !!collection.find(i => i !== item && i.phone === item.phone && i.name === item.name);
return item;
});
Here you're just using map to iterate through and check if each item has a duplicate that isn't the original.
回答3:
Create a hash function for your object type.
A simple concatenation of the fields seems to work in this case. Iterate through your collection and for each element, hash it, and put it in a table.
Keep track of the counts. When the count is greater than 1 you know you have a duplicate (row match)
JavaScript Hashmap Equivalent
回答4:
use Array.prototype.find
var newCollection = collection.map((row, index) => {
if(row["rowMatch"])
return row;
rowMatch = !!collection.find((r,i) => i !== index && r.name === row.name && r.phone === row.phone);
row["rowMatch"] = rowMatch;
return row;
})
来源:https://stackoverflow.com/questions/47163806/how-to-compare-each-object-in-an-array-with-each-other-when-found-update-the-ob