WBC
WBC

Reputation: 1914

How to loop through specific keys in nested object?

I want to pull specific parts (definitely not all) from this object:

var metadata = {
    cat: {
        id: 'id',
        name: 'kitty',

    },    
    dog: {
        id: 'id',
        name: 'spot',
        owner: {
            name: 'ralph',
        }
    }    
    //tons of other stuff
};

I would like to do something like this:

var fields = ['cat.id', 'dog.name', 'dog.owner.name'];
fields.forEach( function(key) {
    console.log(metadata[key]); //obv doesn't work
});

This is a simplified scenario where I'm trying to validate specific fields in metadata. Is there a straightforward way to do this?

Upvotes: 0

Views: 52

Answers (1)

elclanrs
elclanrs

Reputation: 94101

Split the path to extract individual keys, then use a reducer to resolve the value, then map the results:

var path = function(obj, key) {
  return key
    .split('.')
    .reduce(function(acc, k){return acc[k]}, obj)
}

var result = fields.map(path.bind(null, metadata))
//^ ['id', 'spot', 'ralph']

Now you can log them out if you want:

result.forEach(console.log.bind(console))

Upvotes: 2

Related Questions