简体   繁体   中英

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

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM