WhoAmI
WhoAmI

Reputation: 317

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 ?

Upvotes: 0

Views: 12538

Answers (3)

Shaun Webb
Shaun Webb

Reputation: 426

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

Upvotes: 2

Tobias Fuchs
Tobias Fuchs

Reputation: 938

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)

Upvotes: 1

Lorenz Merdian
Lorenz Merdian

Reputation: 752

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

Upvotes: 4

Related Questions