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 lodash library 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 error whenever you try to pass posts to 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 render function above using json-query:

这是上面使用json-queryrender函数的修改版本:

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]', { 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>
    );
  }
}

翻译自: https://www.freecodecamp.org/news/iterate-through-nested-object-in-react-js/

react js 遍历对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值