Home > Enterprise >  Converting an object in an array to just an object ReactJS
Converting an object in an array to just an object ReactJS

Time:09-05

Here is the received response from API:

[{id:3, name: John-Doe, age: 30}]

the problem is I need to map through this array to use it:

  <>
        {movie.map((item) => {
          return (
            <>
              <h1>{item.name}</h1>
              <p>{item.age}</p>
            </>
          );
        })}
      </>

I don't want to use map, since there will always be the details of just one person in the API's response (only a one-element array). I want to get rid of the array and convert it to an object so that I can use it directly like {item.age} without using map which doesn't make sense for an array with one element.

CodePudding user response:

You can also destructure the array:

function MyComponent() {
  const [movie] = [{ id: 3, name: John - Doe, age: 30 }];

  return (
    <>
      <h1>{movie.name}</h1>
      <p>{movie.age}</p>
    </>
  );
}

CodePudding user response:

1 - You can access the values directly like this :

function Test() {
  const movie = [{ id: 3, name: 'John - Doe', age: 30 }];

  return (
    <>
      <h1>movie[0].name</h1>
      <p>{movie[0].age}</p>
    </>
  );
}

2 - Or extract the object inside movie array and store it in a variable like this :

function Test() {
  const movie = [{ id: 3, name: 'John - Doe', age: 30 }];
  const movieObj = movie[0]

  return (
    <>
      <h1>{movieObj.name}</h1>
      <p>{movieObj.age}</p>
    </>
  );
}
  • Related