Remove key-value pair from JSON object

I have this JSON object below;

[
    {
        XXX: "2",
        YYY: "3",
        ZZZ: "4"
    },
    {
        XXX: "5",
        YYY: "6",
        ZZZ: "7"
    },
    {
        XXX: "1",
        YYY: "2",
        ZZZ: "3"
    }
]

I want to remove the YYY key-value from the json object such that the new json object will look like this;

[
    {
        XXX: "2",       
        ZZZ: "4"
    },
    {
        XXX: "5",       
        ZZZ: "7"
    },
    {
        XXX: "1",       
        ZZZ: "3"
    }
]

I tried delete jsonObject['YYY'] but this is not correct. How can this be done in javascript? Thank you.

Answers:

Answer

What you call your 'JSON Object' is really a JSON Array of Objects. You have to iterate over each and delete each member individually:

for(var i = 0; i < jsonArr.length; i++) {
    delete jsonArry[i]['YYY'];
}
Answer

Iterate over the values in the array, and remove the value with key YYY:

var obj = [
    {
        XXX: "2",
        YYY: "3",
        ZZZ: "4"
    },
    {
        XXX: "5",
        YYY: "6",
        ZZZ: "7"
    },
    {
        XXX: "1",
        YYY: "2",
        ZZZ: "3"
    }
];

for (var i = 0; i < obj.length; i++) {
    delete obj[i].YYY
}
Answer

Another solution that avoids mutating the original array and uses a more modern features (object rest operator & destructuring)

const arr = [
    {
        XXX: "2",
        YYY: "3",
        ZZZ: "4"
    },
    {
        XXX: "5",
        YYY: "6",
        ZZZ: "7"
    },
    {
        XXX: "1",
        YYY: "2",
        ZZZ: "3"
    }
]

// destructure 'YYY' and return the other props only
const newArray = arr.map(({YYY, ...rest}) => rest)

console.log(newArray)

Answer

jsonObject is an array, so you need to reference the array elements. Try delete jsonObject[0].YYY

Answer

JSON is text, so if you really do have text like:

var s = '[{XXX:"2",YYY:"3",ZZZ:"4"},{XXX:"5",YYY:"6",ZZZ:"7"},{XXX:"1",YYY:"2",ZZZ:"3"}]';

then you can remove the YYYs using string replace, something like:

s.replace(/YYY[^,}]+,/g,''); // [{XXX:"2",ZZZ:"4"},{XXX:"5",ZZZ:"7"},{XXX:"1",ZZZ:"3"}]

You may need to account for YYY at the start or end of the string too. If you have an object that is created by an object literal, then use one of the other answers.

Answer

Because your JSON is inside of an array, you need to access each element in the array and delete their properties "YYY" Or use map to create a reduced object, like so:

var objs = [
    {
        XXX: "2",
        YYY: "3",
        ZZZ: "4"
    },
    {
        XXX: "5",
        YYY: "6",
        ZZZ: "7"
    },
    {
        XXX: "1",
        YYY: "2",
        ZZZ: "3"
    }
];

objs = objs.map(function(obj) {
    return { XXX: obj.XXX, ZZZ: obj.ZZZ };
});

Using the map function. MDN: Array.prototype.map()

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.