角度如何用键从数组拼接



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

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

如何重新拼接此值?没有钥匙,这是工作:

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

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

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

然后像往常一样拼接阵列。

this.checkedList.splice(index, 1);

由于这将是插入的最后一个值,您可以简单地从中pop这个值

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

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

// 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((将返回undefined,并且只返回第一个匹配的项!秩序很重要!

最新更新