在对象数组中查找重复值

编程入门 行业动态 更新时间:2024-10-18 10:28:40
本文介绍了在对象数组中查找重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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; }); }

更多推荐

在对象数组中查找重复值

本文发布于:2023-11-07 06:01:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565725.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!