简体   繁体   English

使用angular删除json对象键值

[英]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. 我有json响应,我想从中删除一些对象键值,并将编辑后的响应存储在其他部分,以便我可以再次使用。

I know by using simple javascript, but I don't have any idea in angularjs. 我知道使用简单的javascript,但是我对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 现在我要从这个Json文件中过滤掉

"$id": "41" , "ID": 1 , "Order": 0 , "Delay": 0 , "Groups": [] , "Name": "abc" "$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: 因此,我要存储的新的json结构将如下所示:

{
    "$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. 您可以只使用普通的旧JavaScript。 My apporach iterates through all the items in the ABC array and delete s all properties defined in the props array. 我的方法遍历ABC数组中的所有项目,并delete props数组中定义的所有属性。 Note, that this actively modifies the ABC array items. 请注意,这会主动修改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); 

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. 如果我们有一个名为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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM