0

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

bigLdot
  • 173
  • 1
  • 7
  • 2
    Ur json is incorrect, images should be an object – sridhar.. Jul 24 '18 at 09:02
  • There is no JSON in your question, please read [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – str Jul 24 '18 at 09:13

2 Answers2

1

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.

31piy
  • 23,323
  • 6
  • 47
  • 67
0

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>
sridhar..
  • 1,945
  • 15
  • 19