请指教。我有这个:
var x =[ { id: '1', item: 'item1', price: 'price1' },
{ id: '2', item: 'item2', price: 'price2' }
]
我需要能够不断向这个数组中添加新对象,但唯一的条件是只有 id
应该是唯一的。
所以我不应该添加像
{id: '2', item: 'item3', price: 'price3'}
并且能够添加类似的内容
{id: '3', item: 'item2', price: 'price3'}
如何检查我的那个情况?
基本上,除了 id
之外的所有其他内容都可以重复。
请不要使用 jQuery
。
提前致谢!!!
最佳答案
将所有 id 放入一个数组中,然后检查给定的对象 id 是否在该数组中
例如:
var allids = x.map(obj => obj.id); // Es 6
if(allids.indexOf(currentObj.id) > -1) {
// exist. don't add.
}else {
// add
}
如果你不想要 ES6 行,
var allids = x.map(function(obj) {return obj.id;});
关于javascript - 有一个对象数组,需要添加新的对象。如何检查是否只有一个 key : value pairs exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47451809/