Filtering out keys from a JavaScript object

2019-09-07 14:56发布

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条回答
啃猪蹄的小仙女
2楼-- · 2019-09-07 15:37

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; }))
查看更多
登录 后发表回答