迭代一个嵌套的js对象

时间:2019-03-22 20:53:05

标签: javascript reactjs

我将jsonplaceholder用作我的应用程序状态。当我遍历嵌套对象以显示时,我无法使其工作。例如,我拿了两个

state = {
post: [
  {
    id: 1,
    name: "Leanne Graham",
    username: "Bret",
    email: "Sincere@april.biz",
    address: {
      street: "Kulas Light",
      suite: "Apt. 556",
      city: "Gwenborough",
      zipcode: "92998-3874",
      geo: {
        lat: "-37.3159",
        lng: "81.1496"
      }
    },
    phone: "1-770-736-8031 x56442",
    website: "hildegard.org",
    company: {
      name: "Romaguera-Crona",
      catchPhrase: "Multi-layered client-server neural-net",
      bs: "harness real-time e-markets"
    }
  },
  {
    id: 2,
    name: "Ervin Howell",
    username: "Antonette",
    email: "Shanna@melissa.tv",
    address: {
      street: "Victor Plains",
      suite: "Suite 879",
      city: "Wisokyburgh",
      zipcode: "90566-7771",
      geo: {
        lat: "-43.9509",
        lng: "-34.4618"
      }
    },
    phone: "010-692-6593 x09125",
    website: "anastasia.net",
    company: {
      name: "Deckow-Crist",
      catchPhrase: "Proactive didactic contingency",
      bs: "synergize scalable supply-chains"
    }
  }
]
};

我使用了这种方法

class post extends Component {
  state ={ … }
  render() {
    let nestedObj = null;

if (this.state.post) {
  nestedObj = this.state.post.map(obj => {
    Object.keys(obj.company).map(e => {
      let company= `${obj.company[e]}`;
      console.log(company);
      return (
        <ul>
          <li>{company}</li>
        </ul>
      );
    });
  });
  console.log(nestedObj);
}
return(
  <p>{nestedObj}</p>
  )
 }

即使控制台将它登录到终端,它也不会显示在客户端上,但我尝试使用hasOwnProperty,它还给了我[object object]。其次,我注意到如果我分别使用Object.entries和forEach而不是object.keys和map对其进行管理但不显示它,哪种方法合适?

我的头衔是地址和公司。  预先感谢您的帮助。

0 个答案:

没有答案
相关问题