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


}

Zack Zilic
  • 832
  • 3
  • 12
  • 28
  • 3
    `Object.values(names).map` ...etc – trincot Nov 06 '22 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',..]` – cmgchess Nov 06 '22 at 15:28
  • 1
    "*now I normalized that array*" - what do you mean by "normalisation" here? – Bergi Nov 06 '22 at 15:46
  • @Bergi, I need to work with an object, so I need to convert this array to object; – Zack Zilic Nov 06 '22 at 16:11
  • But *why* do you think you need to work with an object? – Bergi Nov 06 '22 at 16:23
  • @Bergi I want to make my app faster, instead of looping through an array every time I update one element, I want to update elements by ID, and then in DOM, I will update only 1 element, instead of the whole Array. That was an idea that I'm trying to implement – Zack Zilic Nov 06 '22 at 16:29
  • 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. – Bergi Nov 06 '22 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. – James Nov 06 '22 at 17:12

1 Answers1

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>;
};
marcobiedermann
  • 4,317
  • 3
  • 24
  • 37