Angular Array如何用key拼接?

Angular how to splice from Array with key?

我遇到了这个问题,我用这种方式将数据推送到数组中。

this.checkedList.push({"customer_id" : option.id });

如何重新拼接这个值?没有钥匙这是有效的:

this.checkedList.splice(option.id,1);

因为这将是最后插入的值,您可以简单地 pop 这个值输出

let k = [ {name: 'John'},  {name: 'Doe'} ];
k.push({ name: 'Peter'})
console.log(k)
k.pop()
console.log(k)

您可以在数组上使用 findIndex 原型方法来查找您要查找的元素的键,例如

let index = this.checkedList.findIndex((element) => element["customer_id"] == option.id);

然后像往常一样拼接数组。

this.checkedList.splice(index, 1);

您正在向数组末尾添加一个对象。看看下面的片段:

// create an array and add an object to it - retrieve via index
const myArr = [];

const newLengthOfArray = myArr.push({"customer_id": 23});

console.log(`Added an element at index ${newLengthOfArray - 1} now containing ${newLengthOfArray} elements`);

const myObject = myArr[newLengthOfArray - 1];

console.log("Your element:", myObject);

// adding more elements 
myArr.push({"customer_id": 20});
myArr.push({"customer_id": 21});
myArr.push({"customer_id": 27});

// use find(predicate) to find your first object:
const theSameObject = myArr.find(el => el.customer_id === 23);

// be carefull! find will return the FIRST matching element and will return undefined if none matches!
console.log("Your element found with find:", theSameObject);

小心,因为如果没有项目匹配,find() 将 return 未定义,并且只会 return 第一个匹配的项目!顺序很重要!