2

I have the following model attributes:

[{
    "id": 1,
    "details": {
        "name": "Sun Tzu",
        "height": "180",
    },
    "lists": [
        [{
            "coworkers": "company cool",
            "friends": "School",
        }],
        [{
            "coworkers": "company nice",
            "friends": "Childhood",
        }]
    ]
}]

Yes, I know it is confusing but I am trying to understand nested models.

I want to display in a view (a table row), all the friends of id:1 model.
For example: School, Childhood.

How do I do that? Thanks in advance!

Nurdin
  • 23,382
  • 43
  • 130
  • 308

2 Answers2

3
var friends = _.chain(data)
    .findWhere({ id: 1 })
    .result('lists')
    .flatten(false)
    .pluck('friends')
    .value();
Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
1

You can chain functions to get the output you are looking for

console.log(_.chain(data)
    .find(function(currentObject) {
        return currentObject.id === 1;
    })
    .pick("lists")
    .flatten(false)
    .pluck("friends")
    .value());

Output

[ 'School', 'Childhood' ]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497