简体   繁体   中英

es6 destructuring assignment

I'm looping over an object to create number of arrays inside dataSet.

 dataSet = []
     this.props.users.map((item) => {
      dataSet.push([item.profile.firstName, item.profile.lastName])
     })

How can I apply es6 destructuring? here is what I have tried, but keep getting syntax error.

     dataSet = []
     this.props.users.map((item) => {
      let {firstName, lastName } = item.profile
      dataSet.push([firstName, lastName])
     })

First of all, you're creating extra work for yourself by performing push inside of map . Map will return an array for you naturally. Try this snippet out:

 let props = { users: [ { profile: { firstName: "John", lastName: "Doe", sex: "male" } }, { profile: { firstName: "Jane", lastName: "Doe", sex: "female" } } ] }; const newArr = props.users.map(({profile: {firstName, lastName}}) => [firstName, lastName]); console.log(newArr); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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