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?
CodePudding user response:
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);
CodePudding user response:
The problem essentially was that you did return({},{})
instead of return [{},{}]
.
(a,b)
is called a comma expression, and it evaluates the first expression a
and then ignores the result, and then only returns the evaluation of the second expression b
.
const cats = ["Tom", "Ginger", "Angela"];
const array = cats.map((element) => [{
name: element,
sex: element !== "Angela" ? "male" : "female"
},
{
age: element !== "Angela" ? "20" : "18",
color:
element === "Tom"
? "black"
: element === "Ginger"
? "orange"
: "white"
}]
);
console.log(array);