Languages

JavaScript - remove key-value pair from JSON object

0 points
Asked by:
sienko
743

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
Answered by:
sienko
743

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

  1. JavaScript - remove property from object

References

  1. delete operator - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join