Reputation: 180
I have this problem I push data this way into array.
this.checkedList.push({"customer_id" : option.id });
How can I splice this value out again? Without key this is working:
this.checkedList.splice(option.id,1);
Upvotes: 0
Views: 5891
Reputation: 470
You are adding an object to the end of your array. Have a look at the following snippet:
// 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);
Be carefull since find() will return undefined if no item matches and will only return the very first item that matches! Order is important!
Upvotes: 0
Reputation: 91
You could use the the findIndex prototype method on the array to find key for the element you're looking for, e.g.
let index = this.checkedList.findIndex((element) => element["customer_id"] == option.id);
and then splice the array as you'd normally do.
this.checkedList.splice(index, 1);
Upvotes: 1
Reputation: 15083
Since this would be the last value inserted, you can simply pop
this value out
let k = [ {name: 'John'}, {name: 'Doe'} ];
k.push({ name: 'Peter'})
console.log(k)
k.pop()
console.log(k)
Upvotes: 0