How to get values ​​in an array from a nested array of objects based on a given condition?

I am using lodash and I have the following array of objects:

[{
    "id": 1,
    "values": [
        {
            "sub": "fr",
            "name": "foobar1"
        }, 
        {
            "sub": "en",
            "name": "foobar2"
        }
    ]
}, 
{
    "id": 2,
    "values": [
        {
            "sub": "fr",
            "name": "foobar3"
        },
        {
            "sub": "en",
             "name": "foobar4"
        }
    ]
}]

That I am trying to get a list of ID and name for the given "SUB". So, with the previous object, if I send sub fr, I want to get:

[{
    "id": 1,
    "name": "foobar1"

}, 
{
    "id": 2,
    "name": "foobar3"
}]

You know, can I easily do this with lodash?

I tried using _.pick, but it does not work (I lost these mixes between nested objects and arrays a bit) _.map(data, function (o) { _.pick(o, ['id', 'values.name']) });.

I also tried using _.filterwith things like _.filter(data, { values: [{ sub: 'fr' }]});, but returned all the elements. I am only looking to return the nested part.

+6
source share
3 answers

flatMap(), subs filter(), map().

var result =  _.flatMap(data, item => 
  _(item.values)
    .filter({ sub: 'fr' })
    .map(v => ({id: item.id, name: v.name}))
    .value()
);

var data = [{
    "id": 1,
    "values": [
        {
            "sub": "fr",
            "name": "foobar1"
        }, 
        {
            "sub": "en",
            "name": "foobar2"
        }
    ]
}, 
{
    "id": 2,
    "values": [
        {
            "sub": "fr",
            "name": "foobar3"
        },
        {
            "sub": "en",
             "name": "foobar4"
        }
    ]
}];

var result =  _.flatMap(data, item => 
  _(item.values)
    .filter({ sub: 'fr' })
    .map(v => ({id: item.id, name: v.name}))
    .value()
);
           
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.js"></script>
+7

@ryeballar,

var result =  _.map(data, item => ({id: item.id, name: item.name}));
+4

Thanks for posting the flatMap method, it is useful to me.

0
source

All Articles