Bala
Bala

Reputation: 11244

How to get inner array of nested object using underscorejs?

I get an array of objects representing books. Book has nested Chapters and each chapter has nested Pages. I am trying to reach pages using where and/or chain and name of the chapter but don't know how to reference pages to iterate and get name and keyword. None of my approaches worked and obviously I am missing a key understanding.

var getPages = function(book, n) {

    _.chain(book.chapters).where({name:n})...how do I refer pages array from here?;

    or

    _.select(_.where(book.chapters,{name:n}), function(p) {
         return p.keyword + p.name;
    };

};

Nested Data:

{
  "name": "Javascript for Dummies",
  "chapters": [
    {
      "name": "Introduction",
      "status": "passed",
      "pages": [
        {
          "name": "page 10",
          "keyword": "objects",
          "status": "passed"
        },
        {
          "name": "page 40",
          "keyword": "methods",
          "status": "failed"
        },
        {
          "name": "",
          "keyword": "",
          "status": ""
        }
      ]
    },
    {
      "name": "Data Types",
      "status": "passed",
      "pages": [
        {
          "name": "page 33",
          "keyword": "Strings",
          "status": "passed"
        },
        {
          "name": "",
          "keyword": "",
          "status": ""
        },
        {
          "name": "",
          "keyword": "",
          "status": ""
        }
      ]
    }
  ],
  "status": "failed"
}

Upvotes: 2

Views: 519

Answers (1)

thefourtheye
thefourtheye

Reputation: 239453

You are almost there, just get only the pages property from all the returned values and flatten them like this

function getPages(book, n) {
    return _.chain(book.chapters).where({
            name: n
        })
        .map(function(currentObject) {
            return currentObject.pages;
        })
        .flatten()
        .value();    
}

Output

[ { name: 'page 10', keyword: 'objects', status: 'passed' },
  { name: 'page 40', keyword: 'methods', status: 'failed' },
  { name: '', keyword: '', status: '' } ]

Here, _.where returns an array and we are just iterating through the array and creating a new array with only the pages object from individual objects. Since there may be more than one matches, the result will be an array of array of pages, so we are flattening it and finally getting the value and returning it.

Upvotes: 3

Related Questions