简体   繁体   English

迭代 JSX 中的 object 属性

[英]Iterate over object properties in JSX

New to React/JSX so please bear with me. React/JSX 新手,请多多包涵。 I have an API that returns an object as follows我有一个 API 返回一个 object 如下

var currObj = {
  SKU : 'Test_SKU_120934',
  category : 'Home',
  inventory_status : 1.
}

I want to iterate over this object and return a html unnumbered list as follows我想遍历这个 object 并返回一个 html 未编号列表,如下所示

<ul>
  <li> <strong>SKU</strong> : 'Test_SKU_120934'</li>
  <li> <strong>category</strong>: 'Home' </li>
  <li> <strong>inventory_status</strong> : 1 </li> 
</ul>
```
I can accomplish this in normal Javascript using 'for...in' loop. However, that loop doesn't return anything. How do I write statement below?
```
render () {
    return (

    );
}
```

as you got the answer in the comment you have to use the map which will return the array of children that will be rendered in the jsx.当您在评论中得到答案时,您必须使用 map 它将返回将在 jsx 中呈现的子数组。

here is the code snippet.这是代码片段。

 /* other react component body. . . */ // targeted object var currObj = { SKU: 'Test_SKU_120934', category: 'Home', inventory_status: 1. } const objectList = Object.keys(currObj).map(k => ( <li key={k} ><strong>{k}</strong>: {currObj[k]}</li> )); return ( <ul>{objectList}</ul> ); // here objectList is returned by the map function. and Object.keys function creates iterable array of keys from object.

Here is what you need.这是你需要的。 Link to the working solution. 链接到工作解决方案。

import "./styles.css";

export default function App() {
  var currObj = {
    SKU: "Test_SKU_120934",
    category: "Home",
    inventory_status: 1
  };

  const objectArr = Object.keys(currObj).map((k, idx) => (
    <li key={idx}>
      <strong>{k}</strong>: {currObj[k]}
    </li>
  ));

  return (
    <div className="App">
      <ul>{objectArr}</ul>
    </div>
  );
}

Object.entries Object.条目

return (
  <ul>
   {Object.entries(yourProp).map(([key,val]) => (
     <li key={key}><strong>{key}</strong>: '{val}'</li>
   ))}
  </ul>
)

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

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