MHD MHD - 3 months ago 7
JSON Question

Create new array from iterating JSON objects and getting only 1 of its inner array

See jsfiddle here: https://jsfiddle.net/remenyLx/2/

I have data that contains objects that each have an array of images. I want only the first image of each object.

var data1 = [
{
id: 1,
images: [
{ name: '1a' },
{ name: '1b' }
]
},
{
id: 2,
images: [
{ name: '2a' },
{ name: '2b' }
]
},
{
id: 3
},
{
id: 4,
images: []
}
];

var filtered = [];
var b = data1.forEach((element, index, array) => {
if(element.images && element.images.length)
filtered.push(element.images[0].name);
});

console.log(filtered);


The output needs to be flat:

['1a', '2a']


How can I make this prettier?

I'm not too familiar with JS
map
,
reduce
and
filter
and I think those would make my code more sensible; the
forEach
feels unnecessary.

Answer

First you can filter out elements without proper images property and then map it to new array:

const filtered = data1
  .filter(e => e.images && e.images.length)
  .map(e => e.images[0].name)

To do this in one loop you can use reduce function:

const filtered = data1.reduce((r, e) => {
  if (e.images && e.images.length) {
    r.push(e.images[0].name)
  }
  return r
}, [])