react js 遍历对象_遍历React.js中的嵌套对象
react js 遍历对象
If you've ever worked with APIs, you'll know that the structure of the data they return can get complicated quickly.
如果您曾经使用过API,就会知道它们返回的数据结构会很快变得复杂。
Imagine you call an API from your React project and the response looks something like this:
想象一下,您从React项目中调用一个API,响应看起来像这样:
Object1 { Object2 { propertyIWantToAcess: anotherpropertyIWantToAcess: } }
You've stored the data within your component's state as
this.state.myPosts, and can access the elements of the outer object with the following:
您已经将数据存储为
this.state.myPosts作为组件状态内的数据,并且可以使用以下命令访问外部对象的元素:
render() { console.log(this.state.myPosts); const data = this.state.myPosts; const display = Object.keys(data).map((d, key) => { return ( <div className="my-posts"> <li key={key}> {data.current_route} </li> </div> ); }); return( <div> <ul> { display } </ul> </div> ); }
But the problem is that you aren't able to access any of the inner objects.
但是问题是您无法访问任何内部对象。
The values of the inner objects will always change, so you aren't able to hardcode their keys and iterate through those to get the proper values.
内部对象的值将始终更改,因此您无法对它们的键进行硬编码并对其进行迭代以获取正确的值。
可能的解决方案 (Possible solutions)
It can be difficult to work directly with complex API responses, so let's take a step back and simplify:
直接处理复杂的API响应可能很困难,因此让我们退后一步并简化一下:
const visit = (obj, fn) => { const values = Object.values(obj) values.forEach(val => val && typeof val === "object" ? visit(val, fn) : fn(val)) } // Quick test const print = (val) => console.log(val) const person = { name: { first: "John", last: "Doe" }, age: 15, secret: { secret2: { secret3: { val: "I ate your cookie" } } } } visit(person, print) /* Output John Doe 15 I ate your cookie */
The
lodashlibrary has simple methods to accomplish the same thing, but this is a quick and dirty way to do the same thing in vanilla JS.
lodash库具有完成相同任务的简单方法,但这是在香草JS中完成相同任务的快速而肮脏的方法。
But say you want to simplify further, something like:
但是说您想进一步简化,例如:
render() { // Logs data console.log(this.state.myPosts); const data = this.state.myPosts; // Stores nested object I want to access in posts variable const posts = data.content; // Successfully logs nested object I want to access console.log(posts); // Error, this will not allow me to pass posts variable to Object.keys const display = Object.keys(posts).map(key => <option value={key}>{posts[key]}</option> ) return( <div> {display} </div> ); }
But you get an error,
TypeError: can't convert undefined to object errorwhenever you try to pass
poststo
Object.keys.
但是,您遇到一个错误,
TypeError: can't convert undefined to object error每当尝试将
posts传递给
Object.keys时,
TypeError: can't convert undefined to object error。
Keep in mind that this error has nothing to do with React. It's illegal to pass an object as a child of a component.
请记住,此错误与React无关。 将对象作为组件的子代传递是非法的。
Object.keys()only returns the keys of the object that's passed in as a parameter. You'll need to call it multiple times to iterate through all the nested keys.
Object.keys()仅返回作为参数传入的对象的键。 您需要多次调用它以遍历所有嵌套键。
If you need to display the whole nested object, one option is to use a function to convert each object into a React component and pass it as an array:
如果需要显示整个嵌套对象,一种选择是使用函数将每个对象转换为React组件并将其作为数组传递:
let data= [] visit(obj, (val) => { data.push(<p>{val}</p>) // wraps any non-object type inside <p> }) ... return <SomeComponent> {data} </SomeComponent>
有用的包裹 (Useful packages)
Another option is to use a package like json-query to help iterate through the nested JSON data.
另一个选择是使用json-query之类的包来帮助迭代嵌套的JSON数据。
Here's a modified version of the
renderfunction above using
json-query:
这是上面使用
json-query的
render函数的修改版本:
render() { const utopian = Object.keys(this.state.utopianCash); console.log(this.state.utopianCash); var author = jsonQuery('[*][author]', { data: this.state.utopianCash }).value var title = jsonQuery('[*][title]', { data: this.state.utopianCash }).value var payout = jsonQuery('[*][total_payout_value]', { data: this.state.utopianCash }).value var postLink = jsonQuery('[*]翻译自: [url=https://www.freecodecamp.org/news/iterate-through-nested-object-in-react-js/]https://www.freecodecamp.org/news/iterate-through-nested-object-in-react-js/" target=_blank>', { data: this.state.utopianCash }).value var pendingPayout = jsonQuery('[*][pending_payout_value]', { data: this.state.utopianCash }).value var netVotes = jsonQuery('[*][net_votes]', { data: this.state.utopianCash }).value let display = utopian.map((post, i) => { return ( <div className="utopian-items"> <p> <strong>Author: </strong> {author[i]} </p> <p> <strong>Title: </strong> <a href={`https://www.steemit.com` + postLink[i]}>{title[i]}</a> </p> <p> <strong>Pending Payout: </strong> {pendingPayout[i]} </p> <p> <strong>Votes: </strong> {netVotes[i]} </p> </div> ); }); return ( <div className="utopian-container"> {display} <User /> </div> ); } }[/code]
翻译自: [url=https://www.freecodecamp.org/news/iterate-through-nested-object-in-react-js/]https://www.freecodecamp.org/news/iterate-through-nested-object-in-react-js/
react js 遍历对象
- js中遍历对象的属性和值
- js中对象和数组的遍历和简单操作
- js中遍历对象的属性和值
- 遍历js对象属性
- JS 数组遍历和对象遍历的方法
- JS遍历对象的几种方法
- js遍历定义之----对象与类的区别
- JS--遍历对象
- 遍历JS对象的属性和方法例子
- js遍历el list对象
- js对象、Array对象及angularjs的遍历
- js遍历对象、遍历数组、js数组方法大全、区分map()和forEach()以及filter()、区分for...in...和for...of...
- js 遍历对象的属性和值
- JS中数组与对象的遍历方法实例小结
- JS遍历对象或者数组
- JS中轻松遍历对象属性的几种方式
- foreach 遍历嵌套对象 + 放回字段中加个一个字段 绑定的饿了吗ui
- JS中如何轻松遍历对象属性的方式总结
- ****ife 递归实现深度克隆(内含JS数据类型判断,对象遍历)****
- vue.js 双层嵌套for遍历的方法详解, 类似php foreach()