Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
mapping and filtering an array of objects with key

I have an array of objects for users:

const users = [
    0: {
        name: "John",
        email: "jsmith@gmail.com"
    },
    1: {
        name: "Bob",
        email: "bsmith@gmail.com"
    }
]

A useState that controls which user id is selected.

const [id, setId] = useState("1");

For example I have a default state set to id=1

I am trying to map and filter through the array of objects above to get the name, and email based on the id inside the array for the object.

Here is the code of what I am trying to do, but it doesn't seem to get the data from array of objects.

{Object.keys(users).filter((user) => user.id === id).map((user, index) => {
    const userDetails = users[user]
    return (
        <div className="profile" key={index}>
            <h1>{userDetails.name}</h1>
            <h1>{userDetails.email}</h1>
        </div>
    );
})}

Any help would be appreciated.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

users is an array of objects. So just use index without filter or map:

const userDetails = users[id]
return (
    <div className="profile">
        <h1>{userDetails.name}</h1>
        <h1>{userDetails.email}</h1>
    </div>
);
about 4 years ago · Juan Pablo Isaza Relatório

0

To add to the accepted answer:

Even if users was an object, Object.keys(users).filter((user) => user.id === id).map() is redundant if you're only interested in a single user. You can just access the users object directly by the selected id as a key.

import { useState } from "react";

const users = {
  0: {
    name: "John",
    email: "jsmith@gmail.com"
  },
  1: {
    name: "Bob",
    email: "bsmith@gmail.com"
  },
  2: {
    name: "Jill",
    email: "jjones@gmail.com"
  },
  3: {
    name: "Joan",
    email: "jjohnson@gmail.com"
  }
};

export default function App() {
  const [selectedUserId, setSelectedUserId] = useState("0");
  return (
    <>
      <div className="profile">
        <h1>{users[selectedUserId].name}</h1>
        <h1>{users[selectedUserId].email}</h1>
      </div>
      <label>
        selected user id:
        <input
          type="number"
          min={0}
          max={Object.keys(users).length - 1}
          value={selectedUserId}
          onChange={(e) => {
            setSelectedUserId(e.target.value);
          }}
        />
      </label>
    </>
  );
}

Edit unruffled-minsky-pgjzh

about 4 years ago · Juan Pablo Isaza Relatório

0

The syntax of your users declaration is wrong. Either change it to an array or an object. Now its a mix of both in wrong syntax.

The following code is a workable sample.

export default function App() {
 const [id, setId] = useState("1");

 const users = {
  0: {
      name: "John",
      email: "jsmith@gmail.com"
  },
  1: {
      name: "Bob",
      email: "bsmith@gmail.com"
  }
 }

  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p>Start editing to see some magic happen :)</p>

      {!!users[id] && <div className="profile">
                        <h1>{ users[id].name}</h1>
                        <h1>{users[id].email}</h1>
                      </div>
      }
   
    </div>
  );
}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda