如何将数组中的每个对象相互比较.找到后,使用新属性更新对象 [英] How to compare each object in an array with each other. When found update the object with a new property

查看:32
本文介绍了如何将数组中的每个对象相互比较.找到后,使用新属性更新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,考虑以下包含对象的数组.

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.

推荐答案

您可以使用newCollection或像这样在集合中进行操作

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)

就是这样.这里正在为JSFiddle工作. https://jsfiddle.net/touqeer/pgdsw9Le/1/ .

Simple is that.Here is working JSFiddle for it https://jsfiddle.net/touqeer/pgdsw9Le/1/ .

这篇关于如何将数组中的每个对象相互比较.找到后,使用新属性更新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆