-1

I use the JavaScript Array map() Method to iterate an array and render HTML to my page. For example, I have ["Mike", "David", "Peter", Steve"] I can render them with Reach this way:

const RenderNames = () => {
  let names = ["Mike", "David", "Peter", "Steve"];

  const renderNames = (allNames) => {
    return allNames.map( (name) => {
      return <div> hello {name} </div>
    }
  }
  
  return (
    <div> {renderNames(names)} </div>
  )


}

Ok, now I need to normalize that array to get an object like this: {"243fx": "Mike", "g3Frt": "David", "8879a": "Peter", "dkr45": "Steve"}

so how can I loop through this object and render all these elements?

const RenderNames = () => {
  let names = {"243fx": "Mike", "g3Frt": "David", "8879a": "Peter", "dkr45": "Steve"};

  const renderNames = (allNames) => {
    ????
    ????
  }
  
  return (
    <div> {renderNames(names)} </div>
  )


}

8
  • 3
    Object.values(names).map ...etc Commented Nov 6, 2022 at 15:28
  • Object.entries(allNames) will convert object into array like [['243fx','Mike'],...]. Object.values will give ['Mike','David'..] and Object.keys will give ['243fx',..] Commented Nov 6, 2022 at 15:28
  • 1
    "now I normalized that array" - what do you mean by "normalisation" here? Commented Nov 6, 2022 at 15:46
  • 1
    That's not how React works. It will always loop through all elements, regardless whether you use an array or an object to contain them. Commented Nov 6, 2022 at 16:31
  • 1
    Array is usually the right choice for a list of records. Converting to object means you need to convert it back to an array each time you want to iterate it. Commented Nov 6, 2022 at 17:12

1 Answer 1

1

You have to use Object.entries to loop over the object which will give you the key (property name) and its value

const RenderNames = () => {
  const names = {
    "243fx": "Mike",
    g3Frt: "David",
    "8879a": "Peter",
    dkr45: "Steve",
  };

  const renderNames = (allNames) => {
    return Object.entries(allNames).map(([_key, value]) => <div>hello {value}</div>);
  };

  return <div> {renderNames(names)} </div>;
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.