我正在尝试编写一个基本函数,该函数将根据此对象中作为属性的唯一ID来确定对象数组中是否已存在该对象。在搜索时,我想出了这个代码,它似乎做得很好,但我可以想象有一种更好更快的方法来确定是否推送或更新对象。如果你能分享你最好的答案,请...
var myArray = [
{
id: 1,
car: "Ford"
},
{
id: 2,
car: "Honda"
}
];
var objToOverwrite = {
id: 1,
car: "Bentley" // to overwrite car: "Ford"
};
var objToPush = {
id: 3,
car: "Toyota"
};
function pushToArray ( arr, obj ) {
var existingIds = arr.map((obj) => obj.id);
if (! existingIds.includes(obj.id)) {
arr.push(obj);
} else {
arr.forEach((element, index) => {
if (element.id === obj.id) {
arr[index] = obj;
};
});
};
};
pushToArray ( myArray, objToPush );
console.log(myArray);
答案 0 :(得分:1)
如果你想将其减少到1次迭代,你可以这样做: (注意这是你的代码的不可变版本,因此它将返回一个包含结果的新数组,而不是改变原始数组)
function pushToArray ( arr, obj ) {
let updated = false
let result = arr.map(el => {
if (obj.id === el.id) {
updated = true
return obj
// or maybe you want to merge objects here? return Object.assign({}, el, obj)
}
return el
})
if (!updated) {
result.push(obj)
}
return result
}
您还可以考虑使用由id
键入的对象而不是数组。它会简化逻辑:
let cars = {
1: {
id: 1,
car: 'Ford',
},
2: {
id: 2,
car: 'Honda',
}
}
function updateData ( data, obj ) {
// again, an immutable version. You can make this mutable by removing the first {}
return Object.assign({}, data, {
[obj.id]: obj
})
}
并且您可以随时将值转换为数组:
Object.values(cars) // => your original array
答案 1 :(得分:0)
管理好用旧的香草JS编写代码:
function pushToArray(arr, obj) {
var value = obj.id;
var found = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i].id === value) {
arr[i] = obj;
found = true;
}
};
if (!found) arr.push(obj);
};
var myArray = [
{
id: 1,
car: "Ford"
},
{
id: 2,
car: "Honda"
}
];
var objToOverwrite = {
id: 1,
car: "Bentley" // to overwrite car: "Ford"
};
var objToPush = {
id: 3,
car: "Toyota"
};
pushToArray(myArray, objToOverwrite);
console.log(myArray);
&#13;