Filtering out keys from a JavaScript object

旧时模样 提交于 2019-12-12 03:18:35

问题


I have a JavaScript object in the below format

{
"Node1": [
    {
    "Node2": "node2detail1",
    "Node3": "node3detail1",
    "Node4": [
        "node4detail1",
        ]
    },
    {
    "Node2": "node2detail2",
    "Node3": "node3detail2",
    "Node4": [
        "node4detail2",
        ]
    },
    {
    "Node2": "node2detail3",
    "Node3": "node3detail3",
    "Node4": [
        "node4detail3",
        ]
    }
]}

Is it possible to write an jsonpath expression which would result in a JavaScript object in the following format? The intention is to filter by keys.

{
"Node1": [
    {
    "Node2": "node2detail1",
    "Node3": "node3detail1",
    },
    {
    "Node2": "node2detail2",
    "Node3": "node3detail2",
    },
    {
    "Node2": "node2detail3",
    "Node3": "node3detail3",
    }
]}

回答1:


Jsonpath is for extracting values, not filtering JavaScript objects. You can filter your object with:

{Node1: obj.Node1.map(function(o) { return {Node2: o.Node2, Node3: o.Node3}; })}

If you prefer to use Underscore, there is _.pick:

{Node1: _.map(obj.Node1, function(o) { return _.pick(o, 'Node2', 'Node3'); })}

If ES6/Harmony is your thing, define the map function as an arrow function with deconstructed parameters and implicit return value using simplified object literal syntax:

{Node1: obj.Node1.map(({Node2, Node3}) => ({Node2, Node3}))}

Destructively transform:

obj.Node1.forEach(function(o) { delete o.Node4; })

If it suits your fancy, you can use the property filtering capability of JSON.stringify. The array specifies keys to be serialized into the JSON string; others are ignored.

JSON.parse(JSON.stringify(obj, ['Node1', 'Node2', 'Node3']))

Or you could specify a replacer function (taking key and value parameters) and kill Node4 by returningundefined which means to skip that key and its value:

JSON.parse(JSON.stringify(obj, function(k, v) { if (k !== 'Node4') return v; }))


来源:https://stackoverflow.com/questions/25527554/filtering-out-keys-from-a-javascript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!