简体   繁体   English

如何在 Reactjs 中的 object 中显示数组的内容

[英]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):当用户进行表单选择时,它会检索以下 object(object 的内容取决于所做的选择):

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.无法读取未定义的属性“0”。

And when I try it in the browser console I get "Uncaught SyntaxError: Malformed arrow function parameter list".当我在浏览器控制台中尝试时,我得到“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 Object.entries方法是从 object 获取数组,但是你的“值”已经是数组了,所以直接使用map

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

You don't really need Object.entries() .你真的不需要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> .只需在jsonObj.values上使用.map()并在每次迭代时访问当前元素数组并为<label>显示e[0]e[1]

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!我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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