EN
JavaScript - remove key-value pair from JSON object
1
answers
0
points
I have the following JSON object:
var jsonObject = [
{
a: '1',
b: '2',
c: '3',
},
{
a: '4',
b: '5',
c: '6',
},
{
a: '7',
b: '8',
c: '9',
},
];
I want to remove the b key/value from the JSON object so the new JSON object will look like this:
var jsonObject = [
{
a: '1',
c: '3',
},
{
a: '4',
c: '6',
},
{
a: '7',
c: '9',
},
];
I tried delete jsonObject['b'] but this doesn't work.
Can you help me with this?
1 answer
0
points
Your JSON Object is actually an Array of Objects.
You need to loop over the array and delete each object's property individually using delete operator.
Practical example:
// ONLINE-RUNNER:browser;
var jsonArray = [
{
a: '1',
b: '2',
c: '3',
},
{
a: '4',
b: '5',
c: '6',
},
{
a: '7',
b: '8',
c: '9',
},
];
for (var i = 0; i < jsonArray.length; ++i) {
delete jsonArray[i]['b'];
}
console.log(JSON.stringify(jsonArray, null, 4)); // [ { a: '1', c: '3' }, { a: '4', c: '6' }, { a: '7', c: '9' } ]
See also
References
0 comments
Add comment