Johnatan De Leon
Johnatan De Leon

Reputation: 166

Remove specific element from json array

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

Upvotes: 1

Views: 3768

Answers (2)

claasic
claasic

Reputation: 1050

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.

Upvotes: 2

Steve0
Steve0

Reputation: 2243

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

Upvotes: 0

Related Questions