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
asked Aug 14, 2019 at 17:36
Johnatan De Leon
1662 silver badges10 bronze badges
2 Answers 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
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);
answered Aug 14, 2019 at 17:40
Steve0
2,2532 gold badges13 silver badges23 bronze badges
3 Comments
claasic
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?
Steve0
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.
Johnatan De Leon
I use the slice to remove the element. i did something like this: json[place].splice(position, 1); Thanks!
lang-js
splice()to remove an item from an array. --> stackoverflow.com/questions/5767325/…index, you could dodelete json["section"+index]