Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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

share|improve this question
up vote 11 down vote accepted

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

share|improve this answer
1  
Thank you so much !!! – Codrina Valo yesterday

With the use of utility library Lodash, you can use the method find.

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, function(o) {
  return o.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>

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.