Mapping array inside another array using spread operator

I’m testing spread operator inside array to map another array values. Unfortunately, I have come up with weird behavior or I did it wrong. When I return 2 objects using map inside the array, it’s only returning the last object. Code below:

const cats = ["Tom", "Ginger", "Angela"];

const array = [
  // {
  //   name: "Ben",
  //   sex: "male"
  // },
  ...cats.map((element, index, array) => {
    return (
      {
        name: element,
        sex: element !== "Angela" ? "male" : "female"
      },
      {
        age: element !== "Angela" ? "20" : "18",
        color:
          element === "Tom"
            ? "black"
            : element === "Ginger"
            ? "orange"
            : "white"
      }
    );
  })
];

console.log(array);

In console:

[{"age":"20","color":"black"},
{"age":"20","color":"orange"},
{"age":"18","color":"white"}] 

What I expected:

[{"name": "Tom", "sex": "male"},
{"age":"20","color":"black"},
{"name": "Ginger", "sex": "male"},
{"name": "Angela", "sex": "female"},
{"age":"20","color":"orange"},
{"age":"18","color":"white"}]

Codesandbox here. Is it available to implement it what I expected? Or there are other alternatives?

>Solution :

You are returning two objects with a comma. Comma operator will just return the last item. You need to return an array and use flatMap

const cats = ["Tom", "Ginger", "Angela"];
const result = cats.flatMap(x => ([{
  foo: x
}, {
  bar: x
}]));

console.log(result);

Leave a Reply