2

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?

3
  • 2
    return makes no sense, you are returning two objects with a coma operator. It will not return both objects, that is not how that operator works. Commented Jan 24, 2023 at 17:24
  • Also the order looks strange. Why do you expect the first age-color object to come after Tom but then Ginger and Angela following each other. Commented Jan 24, 2023 at 17:28
  • Oops, I confused the order. Commented Jan 24, 2023 at 17:38

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.