简体   繁体   中英

Remove json object key value using angular

I have json response and I want to remove few object key values from it and store the edited response on other part so that I can use again.

I know by using simple javascript, but I don't have any idea in angularjs.

Json response

{
    "$id": "1",
    "XYZ": [],
    "ABC": [
        {
            "$id": "41",
            "ID": 1,
            "Order": 0,
            "Delay": 0,
            "Name": "abc",
            "Count": "9",
            "Storage": 3,
            "Groups": []
        }
    ],
    "Projected": 2019
}

Now from this Json file I want to filter out

"$id": "41" , "ID": 1 , "Order": 0 , "Delay": 0 , "Groups": [] , "Name": "abc"

So my new json structure will be like this which I want to store:

{
    "$id": "1",
    "XYZ": [],
    "ABC": [
        {
            "Count": "9",
            "Storage": 3
        }
    ],
    "Projected": 2019
}

Any method to achieve ?

You don't need some magic angular stuff. You can just use plain old JavaScript. My apporach iterates through all the items in the ABC array and delete s all properties defined in the props array. Note, that this actively modifies the ABC array items.

 const obj = { "$id": "1", "XYZ": [], "ABC": [ { "$id": "41", "ID": 1, "Order": 0, "Delay": 0, "Name": "abc", "Count": "9", "Storage": 3, "Groups": [] } ], "Projected": 2019 } // Now from this Json file I want to filter out const props = ["$id", "ID", "Order", "Delay", "Groups", "Name"]; props.forEach(prop => { obj.ABC.forEach(abc => { delete abc[prop]; }); }); console.log(obj); 

try this

 let json = { "$id": "1", "XYZ": [], "ABC": [ { "$id": "41", "ID": 1, "Order": 0, "Delay": 0, "Name": "abc", "Count": "9", "Storage": 3, "Groups": [] } ], "Projected": 2019 }; json["ABC"] = json["ABC"].map(obj => ({ "Count": obj["Count"], "Storage": obj["Storage"] })); // or dynamic way let keepkeys = ["Storage", "Count"]; json["ABC"] = json["ABC"].map(obj => { let newObj = {}; keepkeys.forEach(key => newObj[key] = obj[key]); return newObj; }); console.log(json) 

An alternative to the other solutions. If we have a variable called json. This method is simple

let len = json.ABC.length;
for (let i=0;i<len;i++){
    delete json.ABC[i].$id;
    delete json.ABC[i].ID;
    delete json.ABC[i].Order;
    delete json.ABC[i].Delay;
    delete json.ABC[i].Groups;
    delete json.ABC[i].Name;
}

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