json - How can i get an array of images from a collection of nested objects with Lodash? -


 {      "shop": {          "homebackground": "http://padmenu.s3.amazonaws.com/15/11/2014/05/08/2ec2ff61-d6a0-11e3-8857-10ddb1e6e201.jpg",          "name": {              "tr": "my shop"          },          "menus": [{                  "name": {                      "en": "menu"                  },                  "children": [{                      "name": {                          "en_us": "category"                      },                      "images": [                          "http://www.progressivedental-ellenlimdds.com/wp-content/uploads/2014/06/red-wine.jpg"                      ],                      "children": [{                          "name": {                              "en_us": "item"                          },                          "images": [                              "http://res.cloudinary.com/finedine/image/upload/c_fill,g_center,h_600/v1435916818/wine-bottle_uz03a0.jpg",                              "http://media.riepenau.com/wines/17973_b.jpg",                              "http://lorempixel.com/400/400/food/3",                              "http://lorempixel.com/400/400/food/4",                              "http://lorempixel.com/400/400/food/5",                              "http://lorempixel.com/400/400/food/6",                              "http://lorempixel.com/400/400/food/7"                          ]                      }]                  }]              }]          }      } 

i want select "images" arrays shop's "children" objects. how can using lodash library? output should array of consists of image urls: ["url1","url2","url3"]

the easiest approach solve problem plucking through children , descendants recursively. important points in getimages() function; wherein flattens children arrays in 1 level, pluck each image arrays , compact items remove undefined values(caused children no images), , flattening images array , readied concatenation. stopping point of recursion when there no images current children, returning empty array. if images found, recursively concatenate potential descendant images. how descendants, use same chaining sequence used in getting images array children plucking key.

demo

function getimages(children) {   var images = _(children).flatten().pluck('images').compact().flatten().value();   if(_.isempty(images)) {     return [];   }   var descendants = _(children).flatten().pluck('children').compact().flatten().value();   return images.concat(getimages(descendants)); }  function getshopimages(data) {   var children = _.pluck(data.shop.menus, 'children');   return getimages(children); }  console.log(getshopimages(data)); 

Comments