gpt4 book ai didi

javascript - 使用javascript将唯一对象插入到对象数组中?

转载 作者:行者123 更新时间:2023-11-28 13:03:42 24 4
gpt4 key购买 nike

我正在对对象数组执行推送操作。我的代码看起来类似如下所示,

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 循环中第二次传递时将其推送到数组。

预期输出应为 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"}];

如何仅将唯一的对象推送到数组?

最佳答案

使用数组.some方法检查列表中是否已存在具有该ID的项目。如果没有,则压入数组:

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 - 使用javascript将唯一对象插入到对象数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48286743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com