0


js 对象数组中查找指定对象的下标并插入新的对象

js 对象数组中查找指定对象的下标并插入新的对象

可以使用 findIndex() 方法来查找数组对象中指定对象的下标。

findIndex() 方法接受一个回调函数作为参数,用于判断每个元素是否符合要求。

回调函数会接受三个参数:当前元素,当前元素的索引,数组本身。

当找到第一个符合要求的元素时,该元素的索引会被返回;否则,返回 -1。

例:

const arr = [
  { id: 1, name: 'foo' },
  { id: 2, name: 'bar' },
  { id: 3, name: 'baz' },
];

我们想查找元素 { id: 2, name: ‘bar’ } 的索引位置,可以这样写:

const targetObj ={id:2,name:'bar'};const index = arr.findIndex((obj)=> obj.id === targetObj.id && obj.name === targetObj.name);
console.log(index);// 1

我们想查找元素 id == 2 的索引位置,可以这样写:

const findId =2;const index = arr.findIndex((obj)=> obj.id === findId);
console.log(index);// 1

在查找到指定对象的下标后,插入一个新的对象。

可以使用 splice() 方法来在数组的指定索引位置插入一个对象。
splice() 方法接受三个参数,
    第一个参数为待插入对象的索引位置,
    第二个参数为要删除的元素个数,
    第三个参数为要插入的对象。

例:
我们想在查找到的位置插入一个新的对象 { id: 4, name: ‘qux’ },可以这样写:

arr.splice(index,0,{id:4,name:'qux'});

我们就会得到:

[
  { id: 1, name: 'foo' },
  { id: 4, name: 'qux' },
  { id: 2, name: 'bar' },
  { id: 3, name: 'baz' },
];

本文转载自: https://blog.csdn.net/qq_39851847/article/details/130218034
版权归原作者 qq_39851847 所有, 如有侵权,请联系我们删除。

“js 对象数组中查找指定对象的下标并插入新的对象”的评论:

还没有评论