2

I have the code below which I expect to map the result from the nested array and return a single array having both id's but I get 2 arrays instead. Can someone please guide me on what I'm doing wrongly?

arrayVal = [{
    sources: {
      data: [{
        id: 1
      }]
    }
  },
  {
    sources: {
      data: [{
        id: 2
      }]
    }
  }
]

for (let sub of arrayVal) {
  let result = sub.sources.data.map(x => (x.id))
  console.log(result)
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Hopez
  • 141
  • 1
  • 9

5 Answers5

4

Right now, you're calling map for each element in arrayVal, so you get two arrays. Use reduce instead, to transform an array of objects into another array that's not necessarily one-to-one with the input elements:

const arrayVal=[{sources:{data:[{id:1}]}},{sources:{data:[{id:2}]}}];

const result = arrayVal.reduce((a, { sources: { data } }) => (
  [...a, ...data.map(({ id }) => id)]
), []);
console.log(result)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
3

arrayVal = [{
    sources: {
      data: [{
        id: 1
      }]
    }
  },
  {
    sources: {
      data: [{
        id: 2
      }]
    }
  }
]

let result = [];
for (let sub of arrayVal) {
  result = result.concat(sub.sources.data.map(x => (x.id)))

}

console.log(result)

I think concat is what you were missing here, Hope this is what you trying to achieve

Gaurav joshi
  • 1,743
  • 1
  • 14
  • 28
3

Try following

var arrayVal = [{sources: {data: [{id: 1}]}},{sources: {data: [{id: 2}]}}];

// Create an array on sources.data and merge it into 1 collection (array)
var result = arrayVal.reduce((a, c) => [...a, ...c.sources.data.map(({id}) => id)], []);

console.log(result);

For reference, Array.reduce

Also, you can improve your code as follows

var arrayVal = [{sources: {data: [{id: 1}]}},{sources: {data: [{id: 2}]}}];

let result = [];
for (let sub of arrayVal) {
  result.push(sub.sources.data.map(x => (x.id)));
}
console.log([].concat(...result))
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1

Try this

arrayVal = [{
    sources: {
      data: [{
        id: 1
      }]
    }
  },
  {
    sources: {
      data: [{
        id: 2
      }]
    }
  }
]

let result = arrayVal.map((x) => x.sources.data[0].id)
console.log(result)
ekbgh
  • 36
  • 3
1

You can do something like this:

arrayVal = [{
    sources: {
      data: [{
        id: 1
      }]
    }
  },
  {
    sources: {
      data: [{
        id: 2
      }]
    }
  }
]

var flat = arrayVal.reduce(function(prev,curr,cI){
  prev.push(curr.sources.data.map(x => (x.id))[0]);
  return prev; // *********  Important ******
}, []);
Neeraj Wadhwa
  • 645
  • 2
  • 7
  • 18