如何使用javascript过滤复杂的json对象?

时间:2016-05-15 17:04:08

标签: javascript jquery json filter

我有以下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)?

由于

2 个答案:

答案 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>');

&#13;
&#13;
def prompt(n):
    value= int(input(print("Please enter integer #", n, ": ",end='')))
    return value
&#13;
&#13;
&#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>