Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 map array of objects to array

There is an array of objects

const data = [{
    "name": "08/20/2018",
    "id": "name_1"
}, {
    "name": "12/23/2018",
    "id": "name_2"
}]

and I would like to map this array of objects in order to get just array

["Date 1","08/20/2018","Date 2","12/23/2018"]

I'm trying using .map()

data.map((d, i) => 
 `${'Date ' + i}`
  d.name
)];

but cannot map name with the first (d) parameter.

like image 910
corry Avatar asked Dec 07 '25 05:12

corry


2 Answers

Because the input items and output array items aren't one-to-one, you won't be able to use .map. Use reduce instead:

const data = [{
    "name": "08/20/2018",
    "id": "name_1"
}, {
    "name": "12/23/2018",
    "id": "name_2"
}];

const output = data.reduce((a, { name }, i) => {
  a.push('Date ' + (i + 1), name);
  return a;
}, []);
console.log(output);

Or .flatMap:

const data = [{
    "name": "08/20/2018",
    "id": "name_1"
}, {
    "name": "12/23/2018",
    "id": "name_2"
}];

const output = data.flatMap(({ name }, i) => (['Date ' + (i + 1), name]));
console.log(output);

(note that since arrays are zero-indexed, you'll have to use i + 1, not i, if you want the first item in the output array to start at 1 instead of 0)

like image 109
CertainPerformance Avatar answered Dec 08 '25 17:12

CertainPerformance


You can't use map since that method produce a new array with the same number of items of the original ones.

However, you can use flatMap (where supported) to achieve the your desired result:

data.flatMap(({name}, i) => [`Date ${i + 1}`, name]);
console.log(data) // [ "Date 1", "08/20/2018", "Date 2", "12/23/2018" ]

Basically flatMap is like calling map and then flat; therefore if from the callback function we returns an array per item, this array will be flattened before returned.

Regular map call would have been produced [[ "Date 1", "08/20/2018"], ["Date 2", "12/23/2018"]] instead.

like image 29
ZER0 Avatar answered Dec 08 '25 18:12

ZER0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!