0

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);

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Good idea. What is idx?
If you check the documentation you see that it's just the current array's index. I just forgot to remove it (as it is not used here) before posting the answer and will do it now as not to confuse anybody else.
0

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)

2 Comments

Thanks, but it is not last value
Noted, Please update the question with more information about the structure of your component
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.