简体   繁体   中英

Get only part of Json object from a Response

How do I return a response with only part of an object

var jason = {
"age" : "24",
"hometown" : "Missoula, MT",
"gender" : "male"
};

If I wanted to return a response only with the key/value pair.

"hometown" : "Missoula, MT"

Oki, I am new at this and thought I could come with a counterexample I tried the dot notation and it simply returned the Value not the key

var stations = [
    {id: 1, description: "London", lat: 64.1275, lon: 21.9028, observations: [2]},
    {id: 2, description: "Spain", lat: 65.6856, lon: 18.1002, observations: [1]}
];

If i loop and use stations[1].description i just get the value "London"

[
{description: "London"};
{description: "Spain"}
] 

This code loops through the object, checks if the key matches the expected key and if the value matched the expected value. If so, it console.log() 's it in the form key : value .

 var jason = { "age" : "24", "hometown" : "Missoula, MT", "gender" : "male" }; var key = "hometown"; var value = "Missoula, MT"; for (var tempKey in jason) { var obj = jason[key]; if (tempKey == key && value == jason[key]) { console.log(key + " : " + jason[key]); } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM