Exploring the spread operator inside an array to map values from another array has led to unexpected behavior. When attempting to return 2 objects using map within the array, only the last object is being returned. Below is the code snippet:
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);
Output in console:
[{"age":"20","color":"black"},
{"age":"20","color":"orange"},
{"age":"18","color":"white"}]
Expected output:
[{"name": "Tom", "sex": "male"},
{"age":"20","color":"black"},
{"name": "Ginger", "sex": "male"},
{"age":"20","color":"orange"},
{"name": "Angela", "sex": "female"},
{"age":"18","color":"white"}]
View on Codesandbox here. Is there a way to achieve the expected outcome or are there other alternatives?