简体   繁体   中英

jQuery/Lodash - Get multiple nested json values by key

I've got a set of json that's being generated for use with other functions.

window.customJSON = {
  "1894873974": {
    title: "Yellow",
    images: [
      {
      main: "/images/img1.jpg",
      alt: "image alt tag"
      },
      {
      main: "/images/img2.jpg",
      alt: "image alt tag"
      }
    ]
  },
  "2397423987": {
    title: "Orange",
    images: [
      {
      main: "/images/img1.jpg",
      alt: "image alt tag"
      }
    ]
  }
}

What I'm trying to do is get all values of 'main' within 'images' for all items and assign them into a single array. The numbers represent unique codes so I'm not trying to get a specific index but all image urls.

I'm using lodash to successfully map other things so I've tried using:

var imgArray = _.map(window.customJSON.images, 'main');

I'm just not quite sure the correct syntax. I've looked through the lodash docs and I haven't been able to google the right combination of words to get an answer.

A jquery or lodash solution would both work.

Thanks

You need to flatMap the images first, before mapping the main attributes. See the working demo below:

 let customJSON = { "1894873974": { title: "Yellow", images: [{ main: "/images/img1.jpg", alt: "image alt tag" }, { main: "/images/img2.jpg", alt: "image alt tag" } ] }, "2397423987": { title: "Orange", images: [{ main: "/images/img1.jpg", alt: "image alt tag" }] } } let result = _(customJSON) .flatMap('images') .map('main') .value(); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script> 

If you need to get only the unique values, apply uniq() before value() as well.

Loop over object keys and map the images..

 let customJSON = { "1894873974": { title: "Yellow", images: [ { main: "/images/img1.jpg", alt: "image alt tag" }, { main: "/images/img2.jpg", alt: "image alt tag" } ] }, "2397423987": { title: "Orange", images: [ { main: "/images/img1.jpg", alt: "image alt tag" } ] } } let res = []; for(var key in customJSON) { let images = customJSON[key]['images']; res = res.concat(images.map(image => image.main)) } console.log(res); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.core.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM