问题描述
我正在对对象数组执行推操作.我的代码如下图所示,
I am performing push operation to an array of objects.My code looks similar as shown below,
var obj = {"id":1, "fname":"john", "lname":"doe"};
var userArray = [{
"id": 1,
"fname": "john",
"lname": "doe"
}, {
"id": 2,
"fname": "john",
"lname": "doe"
}];
userArray.forEach(function (element) {
if(element.id !== obj.id) {
userArray.push(obj);
}
});
console.log(userArray);
当我对已经包含一个要推送的对象的userArray进行推送操作时(根据代码为var obj = {"id":1, "fname":"john", "lname":"doe"};
),它将在第二遍for循环中将其推送到数组.
when i do push operation on userArray which already contains an object which i am pushing (from code it is var obj = {"id":1, "fname":"john", "lname":"doe"};
) it pushes it to array on second pass in for loop.
预期输出应为userArray = [{"id": 1,"fname": "john","lname": "doe"}, {"id": 2, "fname": "john","lname": "doe"}];
但是我得到了userArray = [{"id": 1,"fname": "john","lname": "doe"}, {"id": 2, "fname": "john","lname": "doe"}, {"id": 1,"fname": "john","lname": "doe"}];
如何仅将唯一对象推送到数组?
How do i push only unique objects to array?
推荐答案
使用数组.some
方法检查列表中是否已存在具有该ID的项目.如果没有,则推入数组:
Use the array .some
method to check if there is already an item in the list with that ID. If there isn't, then push into the array:
var obj = {"id":1, "fname":"john", "lname":"doe"};
var userArray = [{
"id": 1,
"fname": "john",
"lname": "doe"
}, {
"id": 2,
"fname": "john",
"lname": "doe"
}];
var existing = userArray.some(element => element.id === obj.id);
if(!existing) {
userArray.push(obj);
}
console.log(userArray);
这篇关于使用JavaScript将唯一对象插入对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!