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"]
3 Answers
Reset to default 13If 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)));
.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 witharr.forEach(...)
? – lurker Commented Feb 15, 2019 at 18:24