简体   繁体   English

array.map()不返回单个数组

[英]array.map() not returning a single array

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. 我有下面的代码,我希望从嵌套数组映射结果,并返回一个具有两个id的单个数组,但我得到2个数组。 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) } 

Right now, you're calling map for each element in arrayVal , so you get two arrays. 现在,您正在为arrayVal 每个元素调用map ,因此您将获得两个数组。 Use reduce instead, to transform an array of objects into another array that's not necessarily one-to-one with the input elements: 使用reduce代替,将一个对象数组转换为另一个数组,该数组不一定与输入元素一对一

 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) 

 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 我认为concat就是你在这里所缺少的,希望这是你想要实现的目标

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 供参考, 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)) 

Try this 尝试这个

 arrayVal = [{ sources: { data: [{ id: 1 }] } }, { sources: { data: [{ id: 2 }] } } ] let result = arrayVal.map((x) => x.sources.data[0].id) console.log(result) 

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 ******
}, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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