I have a JSON array as below:
[{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"address": {
"street":"201 S 4th St.",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
},
"hobbies":[
{
"books":"fiction",
"sports":"football",
"music":"rock"
},
{
"books":"action",
"sports":"cricket",
"music":"jazz"
},
{
"books":"action",
"sports":"cricket",
"music":"cool"
},
]},{
"id":2,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": ["1-770-736-8031 x56442", "4087917884", "4089088939"],
"website": "hildegard.org",
"dept":[{"name":"divya", "address":"abc"},{"name":"divya1", "address":"abc1"}],
"hobbies":[
{
"books":"fiction",
"sports":"football",
"music":"rock"
},
{
"books":"action",
"sports":"cricket",
"music":"jazz"
},
{
"books":"action",
"sports":"cricket",
"music":"cool"
},
]}]
I wanted to use only specific keys only in Hobbies key. Let's say I need only books and sports from Hobbies key. How can I do this in Nodejs? The result should be like below:
[{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"address": {
"street":"201 S 4th St.",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
},
"hobbies":[
{
"books":"fiction",
"sports":"football",
},
{
"books":"action",
"sports":"cricket",
},
{
"books":"action",
"sports":"cricket",
},
] },{
"id":2,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": ["1-770-736-8031 x56442", "4087917884", "4089088939"],
"website": "hildegard.org",
"dept":[{"name":"divya", "address":"abc"},{"name":"divya1", "address":"abc1"}],
"hobbies":[
{
"books":"fiction",
"sports":"football",
},
{
"books":"action",
"sports":"cricket",
},
{
"books":"action",
"sports":"cricket",
},
]}].
Please note that this is just one example. my input is an array of JSON and the keys that I wanted to keep. keys for this example are "id", "name", "hobbies.books", "hobbies.sports" etc.
Given you are using node, I wouldn't reinvent the wheel. So you could use something like the lodash pick
function, alongside map
. For example:
const filteredHobbies = theObject.hobbies.map(item => _.pick(item, ['books', 'sports']))