vanquish vanquish - 4 months ago 7
JSON Question

Javascript- Retrieve specific key values from JSON object

I would like to retrieve only certain key value pair from Json object. Below the list of user with unique ids as keys.

var user = {
"987654321": {
"displayName": "Wayne",
"profilepic": "https://test1.com",
"fullName": "Bruce Wayne",
"Address": "1st Main 1st Cross",
"dob": "Apr 1986",
"likes": "Sports"
},
"123456789": {
"displayName": "wade",
"profilepic": "https://test2.com",
"fullName": "wade wilson",
"Address": "31 Main 1st Cross",
"dob": "Sep 1993",
"likes": "Movies"
}
}
var final = {};
for (var key in user){
final[key] = {"displayName" : user[key]["displayName"]};
final[key] = {"fullName" : user[key]["fullName"]};
final[key] = {"profilepic" : user[key]["profilepic"]};
}
console.log(final);


Below is the output which i get

{
"715886684760616961": {
"profilepic": "https://test1.com"
},
"716503112127758336": {
"profilepic": "https://test2.com"
}
}


I am trying to get displayName, fullName & profilepic. But i am ending up overwriting it with profilepic. Kindly let me know how to fix this.

Thank you

Answer

var user =   {
    "987654321": {
      "displayName": "Wayne",
      "profilepic": "https://test1.com",
      "fullName": "Bruce Wayne",
      "Address": "1st Main 1st Cross",
      "dob": "Apr 1986",
      "likes": "Sports"
    },
    "123456789": {
      "displayName": "wade",
      "profilepic": "https://test2.com",
      "fullName": "wade wilson",
      "Address": "31 Main 1st Cross",
      "dob": "Sep 1993",
      "likes": "Movies"
    }
}
var final = {};
for (var key in user){
final[key] = {"displayName" : user[key]["displayName"],
"fullName" : user[key]["fullName"],
"profilepic" : user[key]["profilepic"]};
}
console.log(final);

Please refer the attached code.. It's simple that you are overwriting values.. so simply append by

final[key] = {"displayName" : user[key]["displayName"], "fullName" : user[key]["fullName"], "profilepic" : user[key]["profilepic"]};

Comments