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

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

.values() is not necessary
@KoushikChatterjee -- thanks for pointing out. Code corrected.
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.