简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM