Javascript:如果元素不存在,如何将其添加到对象中
我想像处理数组一样填充对象 (如果不存在,请添加它)
// push : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
let items = ['aa','xx'];
function newList(item) {
if (items.indexOf(item) === -1) {
items.push(item);
}
return console.log(items)
}
newList('aa');
newList('bb');
newList('aa');
// how i can do the same with this object?
let itemsObj =
[
{id: 'Id AA', name: 'Name AA'},
{id: 'Id BB', name: 'Name BB'},
{id: 'Id CC', name: 'Name CC'},
{id: 'Id DD', name: 'Name DD'},
{id: 'Id EE', name: 'Name EE'},
];
let newItemA = {id: 'Id XX', name: 'Name XX'};
let newItemB = {id: 'Id AA', name: 'Name AA'};
// TODO
答案 0 :(得分:0)
您可以使用“ Array.reduce”和“ Array.from”在“集合”的帮助下实现这一目标
let itemsObj =
[
{id: 'Id AA', name: 'Name AA'},
{id: 'Id BB', name: 'Name BB'},
{id: 'Id CC', name: 'Name CC'},
{id: 'Id DD', name: 'Name DD'},
{id: 'Id EE', name: 'Name EE'},
];
let newItemA = {id: 'Id XX', name: 'Name XX'};
let newItemB = {id: 'Id AA', name: 'Name AA'};
function addItem(item) {
return Array.from(
(itemsObj.concat(item)).reduce((s, d) => s.add(JSON.stringify(d)) , new Set)
, (d) => JSON.parse(d))
}
console.log(addItem(newItemA))
console.log(addItem(newItemB))
答案 1 :(得分:-1)
function addItem(inputItem){
if (!imtemsObj.filter(item => item.id === inputItem.id).length > 0) {
itemsObj.push({id: id, name: name})
}
}
addItem({id: 'Id XX', name: 'Name XX'});
addItem({id: 'Id AA', name: 'Name AA'});