Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{"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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading