1

I have a simple question regarding my React 16.10.0. How do I transform my array into another array of objects? I have an array of objects that have attributes

id
name

And I want to convert that array to another array with attributes

id
text

So I tried

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
     
    const tags = props.values.map(result => 
      {
        id: result.id,
        text: result.name
      });

but the compiler is complaining that a ";" is expected on the "text:" line.

1
  • I think you just missed a return in the map function Commented May 27, 2020 at 16:56

2 Answers 2

2

Javascript is interpreting the { ... } as a block of code instead of an object literal. An easy way to get around that is to just add parenthesis around the object, as in the following:

class MyComponent extends React.Component {
    constructor(props) {
        super(props);

        const tags = props.values.map(result => 
            ({
                id: result.id,
                text: result.name
            }));
Sign up to request clarification or add additional context in comments.

Comments

1

I think you're mixed up because of the implied return not working when returning an object.

There's two ways to return from an arrow function:

Explicit return (block body)

() => {
  return 'something';
}

or Implicit return (concise body)

() => 'something';
() => ('something')

You're attempting to use implicit return, but you're returning an object, so the syntax conflicts with your expectation.

result => 
{
  id: result.id,
  text: result.name
});

This is not an object, but a function body. The function body is invalid syntax leading to the error.

You can fix this by using parenthesis, or by manually returning:

result => 
({
  id: result.id,
  text: result.name
};
result => {
  return {
    id: result.id,
    text: result.name
}};

For reference: check out the section "Returning object literals" in the docs for arrow functions,

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.