在对象数组中查找重复值 [英] Find duplicate values inside array of objects

查看:97
本文介绍了在对象数组中查找重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript中最好的方法是遍历对象数组并检查数组对象的某个属性中是否已存在某个值?
例如:我有以下对象数组:
[{name:team1,members:3},{name:bestteam,members:4}]
现在我想要添加一个新对象,但我想在添加它之前检查数组中是否存在此对象属性name

What is the best way in JavaScript to go over array of object and check if an certain value already exist in one of the property of the array objects? For example: I have array of objects as follow: [{name:"team1",members:3},{name:"bestteam",members:4}] Now I want to add a new object but I want to check that this object property "name" do not exist in the array before adding it

推荐答案

试试这个

function checkIfNameExists(arr, newName) {
    return arr.some(function(e) {
        return e.name === newName;
    });
}

其中arr是你的数组,newName是要检查的名字。

where arr is your array and newName is the name to check.

您还可以通过将属性作为参数传递给比较来减少临时性,例如

You could also make it less ad hoc by passing the property to compare as a parameter, like so

function checkIfNameExists(arr, prop, newVal) {
    return arr.some(function(e) {
        return e[prop] ? e[prop] === newVal : false;
    });
}

这篇关于在对象数组中查找重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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