2

I have:

[{
    "id": 1,
    "listForExtract": [{
        "value1": "1A",
        "value2": "2A"
    }, {
        "value1": "1B",
        "value2": "2B"
    }, ]
},
{
    "id": 2,
    "listForExtract": [{
        "value1": "1C",
        "value2": "2C"
    }, {
        "value1": "1D",
        "value2": "2D"
    }, ]
}]

I want to extract the objects inside listForExtract to a new array like using some function of underscore passing the ID:

something like: _.extractNestedArrayFrom(myArray, 'listForExtract', {'id':2})

[{
    "value1": "1A",
    "value2": "2A"
}, {
    "value1": "1B",
    "value2": "2B"
}]
2
  • Lucas.. you can accept any answer below that you find useful.. Commented Feb 7, 2017 at 16:06
  • I added a comment for finish Commented Feb 7, 2017 at 16:30

3 Answers 3

1

You could use where, pluck and flatten:

var result = _.chain(data)
    .where({id:2})
    .pluck('listForExtract')
    .flatten()
    .value()

Where finds all the items in the array that have an id of 2 and pluck extracts the listForExtract. Flatten is then used to flatten the result into one array

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to return the array rather than array inside another array?
My bad. Added a flatten in there to flatten the array.
1

You don't even need underscore for that.

Following code should work for you.

myArray.filter(function(){
  return o.id==2
}).map(function(o){
  return o.listForExtract
});

2 Comments

Is there a way to return the array rather than array inside another array?
@Lucas.. no matter what u try from underscore.. it will end up with a filter and a map.. so better use that..
1

You can combine map and where methods

var myArray = [{
    "id": 1,
    "listForExtract": [{
        "value1": "1A",
        "value2": "2A"
    }, {
        "value1": "1B",
        "value2": "2B"
    }, ]
},
{
    "id": 2,
    "listForExtract": [{
        "value1": "1C",
        "value2": "2C"
    }, {
        "value1": "1D",
        "value2": "2D"
    }, ]
}];
var result = _.map(_.where(myArray, {
  'id': 2
}), function(elem) {
  return elem.listForExtract
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>

2 Comments

is there a way to return the array rather than array inside another array?
yes try this _.findWhere(myArray, {'id': 2}).listForExtract

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.