Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

往数组对象里面push一个新的对象时,判断如果有id相同的就覆盖这个对象

往数组对象里面push一个新的对象时,判断如果有id相同的就覆盖这个对象改怎么做,用了许多方法去重都是保留原来的对象。。

let arr = [{
    id:'1',
    name:'a'
},{
    id:'2',
    name:'b'
}]

let obj = {
    id:'2',
    name:'c'
}

arr.push(obj)

//console.log(arr)
怎么让打印出来是如下的对象
{
    id:'1',
    name:'a'
},{
    id:'2',
    name:'c'
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
const idx = arr.findIndex(i => i.id == obj.id)
idx < 0 ? arr.push(obj) : arr.splice(idx, 1, obj)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...