问题描述
我有这个问题,我以这种方式将数据推入数组。
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,并且仅返回匹配的第一个项!订单很重要!