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

  • You can use `splice()` to remove an item from an array. --> https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript – daddygames Aug 14 '19 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]` – adiga Aug 14 '19 at 18:20

2 Answers2

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.

claasic
  • 1,040
  • 4
  • 14
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);
Steve0
  • 2,021
  • 2
  • 11
  • 22
  • 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? – claasic Aug 14 '19 at 17:47
  • 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. – Steve0 Aug 14 '19 at 18:52
  • I use the slice to remove the element. i did something like this: json[place].splice(position, 1); Thanks! – Johnatan De Leon Aug 15 '19 at 15:19