Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Filter a complex json object using javascript?

I have the following json object :

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",
    }]
};

How can I filter this object and remain with the HOMES property where home_id = 2 ?

Result:

var json = {
    "Lofts": "none",
    "Maisons": "2",
    "HOMES": [{
        "home_id": "2",
        "price": "1425",
        "num_of_beds": "4",
    }]
};

Is there any way I can cycle the object and mantein all the properties( also lofts and maisons)?

Thanks

like image 294
Codrina Valo Avatar asked May 15 '16 17:05

Codrina Valo


1 Answers

You can use Array#filter and assign the result directly to the property HOMES.

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>');
like image 145
Nina Scholz Avatar answered Oct 08 '22 19:10

Nina Scholz