我有以下json对象:
var json = {
"Lofts": "none",
"Maisons": "2",
"HOMES": [{
"home_id": "1",
"price": "925",
"num_of_beds": "2"
}, {
"home_id": "2",
"price": "1425",
"num_of_beds": "4",
}, {
"home_id": "3",
"price": "333",
"num_of_beds": "5",
}]
};
如何过滤此对象并保留HOMES属性,其中home_id = 2?
结果:
var json = {
"Lofts": "none",
"Maisons": "2",
"HOMES": [{
"home_id": "2",
"price": "1425",
"num_of_beds": "4",
}]
};
有什么方法可以循环对象和mantein所有的属性(也是阁楼和maisons)?
由于
答案 0 :(得分:16)
您可以使用Array#filter
并将结果直接分配给属性var json = { "Lofts": "none", "Maisons": "2", "HOMES": [{ "home_id": "1", "price": "925", "num_of_beds": "2" }, { "home_id": "2", "price": "1425", "num_of_beds": "4", }, { "home_id": "3", "price": "333", "num_of_beds": "5", }] };
json.HOMES = json.HOMES.filter(function (a) {
return a.home_id === '2';
});
document.write('<pre>' + JSON.stringify(json, 0, 4) + '</pre>');
。
def prompt(n):
value= int(input(print("Please enter integer #", n, ": ",end='')))
return value
&#13;
答案 1 :(得分:5)
使用实用程序库Lodash,如果home_id
是唯一的,则可以使用方法find。
查找:迭代collection
(Array | Object)的元素,返回第一个元素predicate
返回truthy for。使用三个参数调用谓词:(value,index | key,collection)。
_.find(collection, [predicate=_.identity])
代码:
var json = {"Lofts": "none","Maisons": "2","HOMES": [{"home_id": "1","price": "925","num_of_beds": "2"}, {"home_id": "2","price": "1425","num_of_beds": "4"}, {"home_id": "3","price": "333","num_of_beds": "5"}]};
json.HOMES = [_.find(json.HOMES, {home_id: '2'})];
document.write('<pre>' + JSON.stringify(json, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.min.js"></script>
如果有多个具有相同home_id
的对象,您应该制作filter:
_.filter(collection, [predicate=_.identity])
过滤器:迭代collection
(Array | Object)的元素,返回所有元素的数组谓词返回truthy for。使用三个参数调用谓词:(value,index | key,collection)。
代码:
var json = {"Lofts": "none","Maisons": "2","HOMES": [{"home_id": "1","price": "925","num_of_beds": "2"}, {"home_id": "2","price": "1425","num_of_beds": "4"}, {"home_id": "3","price": "333","num_of_beds": "5"}]};
json.HOMES = _.filter(json.HOMES, {home_id: '2'});
document.write('<pre>' + JSON.stringify(json, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.min.js"></script>