styler
styler

Reputation: 16491

Get length of object by nested object id?

I'm currently using underscore to the length of an object using _.size(obj) and that is fine but I'm wondering how I could go a little deeper and get the length of objects who's id's equal 123 in my example. I'm not sure if this is something that can be achieved by using underscore or do I need to use a for..in loop and make some kind of count?

JS console.clear();

var obj = {
    'ABC': {
        id: '123',
        name: 'Sesame Street'
    }, 
    'DEF': {
        id: '123',
        name: 'Sesame Street'
    }, 
    'GHI': {
        id: '456',
        name: 'Nowhere Street'
    }
};

console.log('Get length of obj', _.size(obj));
console.log('Get length of obj with id == 123??');

JSFiddle: http://jsfiddle.net/kyllle/0yam33ow/

Upvotes: 0

Views: 83

Answers (1)

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

You could convert your object into an array and use .filter to get the items with only the id 123:

var arr = _.values(obj);
var newObj = arr.filter(function(item){
    return item.id === '123';
});

console.log(_.size(newObj)); // 2

You can do the same thing by using underscores _.where:

var newObj = _.where(obj, {id: '123'});

Fiddle Example

Upvotes: 1

Related Questions