Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

JS 更新数组 里面对象相同的ID的内容

let arr=[ ]
第一次push一个对象 {id:1, text:'11111'}
第二次push一个对象 {id:2, text:'22222'}
此时 let arr=[

{id:1, text:'11111'},
{id:2, text:'22222'}

]

第三次push对象{id:1,text:'33333'}
第三次替换 数组里面ID相同的对象
此时 let arr=[

{id:1, text:'33333'},
{id:2, text:'22222'}

]

同理 第四次push对象 {id:2,text:'44444'}
此时 let arr=[

{id:1, text:'33333'},
{id:2, text:'44444'}

]
请问下 有什么犀利的方法


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

1 Answer

0 votes
by (71.8m points)
const foo = (item, arr) => {
  let targetIndex = arr.findIndex((obj) => obj.id === item.id);
  if (targetIndex === -1) {
    targetIndex = arr.length;
  }

  arr.splice(targetIndex, 1, item);
};

暂时没想到什么犀利的办法。

要不就把这个办法写到 prototype 上?

Array.prototype.uniquePush = function (item) {
  let targetIndex = this.findIndex((obj) => obj.id === item.id);
  if (targetIndex === -1) {
    targetIndex = this.length;
  }

  this.splice(targetIndex, 1, item);
};

// 测试
> const arr = [];
< undefined
> arr.uniquePush({ id: 1, text: '111' });
< undefined
> arr
< [{…}]
  0: {id: 1, text: "111"}
> arr.uniquePush({ id: 2, text: '222' });
< undefined
> arr
< (2)?[{…}, {…}]
  0: {id: 1, text: "111"}
  1: {id: 2, text: "222"}
> arr.uniquePush({ id: 1, text: '333' });
< undefined
> arr
< (2)?[{…}, {…}]
  0: {id: 1, text: "333"}
  1: {id: 2, text: "222"}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...