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"},
{"age":"20","color":"orange"},
{"name": "Angela", "sex": "female"},
{"age":"18","color":"white"}]
Codesandbox here. Is it available to implement it what I expected? Or there are other alternatives?
Via Active questions tagged javascript - Stack Overflow https://ift.tt/MSBcpkj
Comments
Post a Comment