我收到xhr的回复,如下所示:
{
"9994921432": {
"name": "name 1",
"ownerid": "543624"
},
"9979509360": {
"name": "some name",
"ownerid": "765875"
},
"9979524523": {
"name": "some other name",
"ownerid": "215654"
},
"9979524523": {
"name": "some name",
"ownerid": "65893"
}
}
我试图根据“名称”的值过滤它,如果可能的话,使用“一行”(我不能使用jQuery)。我正在测试这样的事情:
var response = '{ "9994921432": { "name": "the name", "ownerid": "543624" }, "9979509360": { "name": "some name", "ownerid": "765875" }, "9979524523": { "name": "some name", "ownerid": "215654" }, "9979524523": { "name": "some other name", "ownerid": "65893" } }';
var json = JSON.parse( '[' + response + ']' );
var filtered = json.filter( function ( item ) { return item.name == 'some name' } );
console.log( filtered );
但是filtered
是空的。
如何获取json
之类的对象,但只包含name == "some name"
的对象?
答案 0 :(得分:1)
尝试如下。你必须遍历对象而不是数组。
var response = '{ "9994921432": { "name": "the name", "ownerid": "543624" }, "9979509360": { "name": "some name", "ownerid": "765875" }, "9979524523": { "name": "some name", "ownerid": "215654" }, "9979524524": { "name": "some other name", "ownerid": "65893" } }';
var json = [];
var resObj = JSON.parse(response);
for(var key in resObj) {
if(resObj[key].name == 'some name') {
json.push(resObj[key]);
}
}
console.log(json);

答案 1 :(得分:0)
使用此代码解决它:
var response = '{ "9994921432": { "name": "the name", "ownerid": "543624" }, "9979509360": { "name": "some name", "ownerid": "765875" }, "9979524523": { "name": "some name", "ownerid": "215654" }, "45756745675": { "name": "some name", "ownerid": "65893" } }';
var json = JSON.parse( response );
var filtered = {};
Object.keys( json ).forEach( function( key ) {
if( json[key].name == "some name" ) {
filtered[key] = json[key];
}
});
console.log( filtered );
不是我想要的单行,而是完成工作。