使用angular删除json对象键值

时间:2018-05-18 08:36:57

标签: javascript angularjs json

我有json响应,我想从中删除一些对象键值,并将编辑后的响应存储在其他部分,以便我可以再次使用。

我知道使用简单的javascript,但我对angularjs没有任何想法。

Json回复

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

现在从这个Json文件中我想过滤掉

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

所以我的新json结构就像我要存储的那样:

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

要实现的任何方法吗?

3 个答案:

答案 0 :(得分:2)

你不需要一些神奇的角色。你可以使用普通的旧JavaScript。 我的apporach遍历ABC数组中的所有项目以及delete数组中定义的所有属性props。请注意,这会主动修改ABC数组项。

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

答案 1 :(得分:1)

试试这个



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)




答案 2 :(得分:0)

其他解决方案的替代方案。 如果我们有一个名为json的变量。 这种方法很简单

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