How to Filter a complex json object using javascript?
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>');
With the use of utility library Lodash, you can use the method find if home_id
is unique.
Find: Iterates over elements of collection
(Array|Object), returning the first element predicate
returns truthy for. The predicate is invoked with three arguments: (value, index|key, collection).
_.find(collection, [predicate=_.identity])
Code:
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>
If there are multiple objects with the same home_id
you should make a filter:
_.filter(collection, [predicate=_.identity])
Filter: Iterates over elements of collection
(Array|Object), returning an array of all elements predicate returns truthy for. The predicate is invoked with three arguments: (value, index|key, collection).
Code:
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>