Katie7
Katie7

Reputation: 879

How to display the content of an array inside an object in Reactjs

I have a React component. When the user makes a form selection, it retrieves the following object (the content of the object varies depending on the selection made):

Data

jsonObj={
 "name":"main",
 "type":"meat",
 "values":[
      ["chicken","Roast chicken with vegetables"],
      ["beef","Beef and Yorkshire pudding"]
]}

Desired results

Here's what I want to display on screen when rendered:

<div>
    <label htmlFor="chicken">Roast chicken and vegetables</label>
</div>
<div>
    <label htmlFor="beef">Beef and Yorkshire pudding</label>
</div>

My failed attempt!

Object.entries(jsonObj["values"]).map(([val,index]))=>{
    return(
        <div>
            <label htmlFor={val[index][0]}>{jsonSub[key][1]}:</label>
        </div>
    )
}

The result of this is:

Cannot read property '0' of undefined.

And when I try it in the browser console I get "Uncaught SyntaxError: Malformed arrow function parameter list". Is anyone able to help me get my desired results?!

Many thanks!

Katie

Upvotes: 2

Views: 5081

Answers (2)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Object.entries method is meant to get array from object, But your "values" is already array, So directly use the map

jsonObj["values"].map(([html, text]) => (
  <div>
    <label htmlFor={html}>{text}</label>
  </div>
));

Upvotes: 2

norbitrial
norbitrial

Reputation: 15166

You don't really need Object.entries(). Simply using .map() on jsonObj.values and accessing on each iteration the current array of elements and showing up e[0] and e[1] for <label>.

Instead you can do it easier like the following:

jsonObj.values.map(e => {
   return <div>
       <label htmlFor={e[0]}>{e[1]}</label>
   </div>
});

See the following example:

const jsonObj = {
 "name":"main",
 "type":"meat",
 "values":[
      ["chicken","Roast chicken with vegetables"],
      ["beef","Beef and Yorkshire pudding"]
]}

const result = jsonObj.values.map(e => {
   // just returning a template literal for representation
   return `<label htmlFor="${e[0]}">${e[1]}</label>`;
});

console.log(result)

I hope this helps!

Upvotes: 1

Related Questions