我该如何只返回一部分对象的响应
var jason = {
"age" : "24",
"hometown" : "Missoula, MT",
"gender" : "male"
};
如果我只想返回键/值对的响应。
"hometown" : "Missoula, MT"
好吧,我是新来的,我想我可以举一个反例,尝试点符号,它只是返回值而不是键
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]}
];
如果我循环使用车站[1]。说明,我只会得到值“伦敦”
[
{description: "London"};
{description: "Spain"}
]
答案 0 :(得分:2)
此代码循环遍历对象,检查键是否与期望的键匹配,以及值是否与期望的值匹配。如果是这样,则console.log()
的格式为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]);
}
}