0

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?

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

4 Comments

sorry I can't seem to follow what the code is doing, would you mind explaining a bit? I've worked with the individual functions but can't seem to piece them together like you've done.
What exactly don't you understand? What method in particular?
I don't understand the path.bind part. Is this how the flow goes? In fields.map, a field, say, 'cat.id' gets passed to path, and reduce calls metadata[cat], metadata[cat][id], finally returns that value? Why is path.bind(null) necessary?
map expects a function; bind partially applies a function where this is the first argument which is not needed, thus null. You could write it with an extra anonymous function: fields.map(function(x){return path(metadata, x)}).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.