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",
}
]}
Jsonpath is for extracting values, not filtering JavaScript objects. You can filter your object with:
If you prefer to use Underscore, there is
_.pick
: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:
Destructively transform:
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.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: