使用地图从数组中解构对象? [英] Destructuring objects from an array using map?
本文介绍了使用地图从数组中解构对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经编写了这个简单的代码,该代码解构了一个对象数组,以从每个键构建新的数组.我正在学习ES6,并希望使用解构将其重构为一行代码,但是我也不太了解.
I have wrote this simple code that destructures an array of objects to build new arrays from each key. I am learning ES6 and would like to refactor it into one line of code using destructuring but I dont fully understand how too.
let candles = [{
open: 1,
high: 2,
low: 0.5,
close: 1.5,
volume: 200
}];
let open = candles.map(x => x.open);
let high = candles.map(x => x.high);
let low = candles.map(x => x.low);
let close = candles.map(x => x.close);
let volume = candles.map(x => x.volume);
console.log(open, high, low, close, volume);
我认为它应该看起来与此类似?
I am thinking it should look something along the lines of this?
let [open, high, low, close, volume] = candles.map(key => key.value);
但这显然是错误的! 如果有人可以指导我正确的方法,谢谢您的帮助!
But it is clearly wrong! Thank you for help if someone can direct me the correct way on doing this!
推荐答案
以下是使用Array.prototype.reduce()
的解决方案:
Here's a solution using Array.prototype.reduce()
:
const candles = [{open: 1, close: 2, low: 3, high: 4, volume: 5}, {open: 6, close: 7, low: 8, high: 9, volume: 10}];
const result = candles.reduce((a, v) => {
Object.keys(v).forEach(k => (a[k] = a[k] || []).push(v[k]));
return a;
}, {});
console.log(result);
这篇关于使用地图从数组中解构对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文