使用es6解构对象数组 [英] Destructuring an array of objects with es6

查看:85
本文介绍了使用es6解构对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将具有三个属性的对象数组分解为三个单独的数组

I am trying to destructure an array of objects with three properties into three separate arrays for example

也许像

const {wlAddresses,wlTokens,wlTickets} = Object.map()

const [wlAddresses,wlTokens,wlTickets] = Object.map()

Object.map()返回类似

Where Object.map() returns something like this

[{ wlAddresses: '23',
    wlTokens: 1,
    wlTickets: 3 },
  { wlAddresses: '24',
    wlTokens: 1,
    wlTickets: 2 },
  { wlAddresses: '25',
    wlTokens: 1,
    wlTickets: 3 }]

我尝试了该方法,它仅返回第一个对象,而不返回后面的对象.我知道我可以通过映射对象并将所有内容返回为单独的数组来解决此问题,但是也许我可以使用解构来做到这一点.

I tried with that method and it only returns the first object, not the ones after. I know I can solve this problem by mapping the object and returning everything as separate arrays but maybe I can use destructuring to do this.

注意:这只是一个问题,是否可以解决,我并没有强迫答案

NOTE: Its just a question of can be done or not, I am not forcing an answer

推荐答案

当您有一个对象或数组并且需要拉出特定项时,解构非常有用,但这不是这种情况.您的数据不是简单的对象或数组,而是对象的数组.您将无法通过简单的任务就可以做到这一点.您将需要将数据转换为所需的格式.例如这样的东西:

Destructuring is great when you have an object or array and need to pull out specific items, but that's not the case here. Your data is not a simple object or array — it's an array of objects. You're not going to be able to do this with a simple assignment. You will need to transform your data into the format you want. For example something like this:

let arr = [{
    wlAddresses: '23',
    wlTokens: 1,
    wlTickets: 3
  },
  {
    wlAddresses: '24',
    wlTokens: 1,
    wlTickets: 2
  },
  {
    wlAddresses: '25',
    wlTokens: 1,
    wlTickets: 3
  }
]

let r = arr.reduce((acc, curr) => {
    for ([key, value] of Object.entries(curr)) {
        if (! acc[key]) acc[key] = []
        acc[key].push( curr[key])
    }
    return acc
}, {})


const {wlAddresses,wlTokens,wlTickets} = r

console.log(wlAddresses,wlTokens,wlTickets)

这篇关于使用es6解构对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆