最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create list of arrays using map? - Stack Overflow

programmeradmin3浏览0评论

Suppose I have this array of object:

let arr = 
[
   { id: "1"},
   { id: "2"},
   { id: "3"}
]

I would create a list of arrays, so I tried:

arr.map(x => x.id);

but this will return:

["1", "2", "3"]

I want an array for each value, eg: ["1"] ["2"] ["3"]

Suppose I have this array of object:

let arr = 
[
   { id: "1"},
   { id: "2"},
   { id: "3"}
]

I would create a list of arrays, so I tried:

arr.map(x => x.id);

but this will return:

["1", "2", "3"]

I want an array for each value, eg: ["1"] ["2"] ["3"]

Share Improve this question edited Feb 15, 2019 at 18:20 sfarzoso asked Feb 15, 2019 at 18:16 sfarzososfarzoso 1,6006 gold badges30 silver badges82 bronze badges 4
  • So return an array? – SLaks Commented Feb 15, 2019 at 18:18
  • Are you after an array of small arrays then? What you show that you want isn't a single entity. – lurker Commented Feb 15, 2019 at 18:18
  • @lurker the expected result is three array, each array have a value – sfarzoso Commented Feb 15, 2019 at 18:19
  • .map isn't going to create three independent arrays ["1"] ["2"] ["3"]. It can, however, create an array of arrays, [["1"], ["2"], ["3"]]. If you want them individually, you probably want to do something with arr.forEach(...)? – lurker Commented Feb 15, 2019 at 18:24
Add a comment  | 

3 Answers 3

Reset to default 13

If you want an array of each then do

arr.map(x=>[x.id]);

try this

arr.map(x => [x.id]);

Note that if you want to get an array with all the object values, you can use Object.values(). This will work for object with one key and for objects with multiple keys.

let arr = 
[
   {id: "1", foo:"bar"},
   {id: "2"},
   {id: "3"}
];

console.log(arr.map(x => Object.values(x)));

Other useful cases could be:

1) Get an array with the keys for each object => Object.keys()

let arr = 
[
   {id: "1", foo:"bar"},
   {id: "2"},
   {id: "3"}
];

console.log(arr.map(x => Object.keys(x)));

2) Get an array with the pairs of [key, value] (entries) for each object => Object.entries()

let arr = 
[
   {id: "1", foo:"bar"},
   {id: "2"},
   {id: "3"}
];

console.log(arr.map(x => Object.entries(x)));

发布评论

评论列表(0)

  1. 暂无评论