1

i declarate a JSON like this

var json{
section1: [],
section2: [],
section3: []
} 

i want to remove a specific item of this way or something like

json[section][index].remove();

i tried with this way

 delete json[section][index];

but when i do this the array elements don't rearrange

2
  • You can use splice() to remove an item from an array. --> stackoverflow.com/questions/5767325/… Commented Aug 14, 2019 at 17:41
  • If you just want to delete a specific property based on a number called index, you could do delete json["section"+index] Commented Aug 14, 2019 at 18:20

2 Answers 2

2

Arrays don't have an remove function. Use splice instead:

var data = {section1: [1,2,3,4]};

const remove = (arr, key, index) => arr[key].splice(index,1)

remove(data,"section1",2)

console.log(data)

Keep in mind that this actually changes the original array.

Sign up to request clarification or add additional context in comments.

Comments

0

slice() is your friend.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

json[section] = json[section].slice(index,index+1);

3 Comments

Slice will return a shallow copy (in this case of a single element of the array). You won't change the original array, you won't return any kind of changed array. Did you mix up slice with splice?
Admittedly it was unclear in the question if the array that they were manipulating was more than a simple array. @assoron, your answer is better anyway. I will leave this one here for completeness I guess.
I use the slice to remove the element. i did something like this: json[place].splice(position, 1); Thanks!

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.