使用地图从数组中解构对象?

时间:2019-01-30 01:03:27

标签: javascript ecmascript-6

我已经编写了这个简单的代码,该代码解构了一个对象数组,以从每个键构建新的数组。我正在学习ES6,并希望使用解构将其重构为一行代码,但我也不太了解。

2

我认为它应该看起来与此类似?

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);

但这显然是错误的! 如果有人可以指导我正确的方法,谢谢您的帮助!

5 个答案:

答案 0 :(得分:2)

这是使用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);

答案 1 :(得分:0)

let candles = [ {
  open: 1,
  high: 2,
  low: 0.5,
  close: 1.5,
  volume: 200
} ]

const { open, high, low, close, volume } = candles.reduce( ( accumulator, item ) => {
    Object.keys( item ).forEach( key => {
        accumulator[ key ] = ( accumulator[ key ] || [] ).concat( item[ key ] ) 
    } )
    return accumulator
}, {} )

答案 2 :(得分:0)

因此,您应该首先从reduce开始并返回一个对象。然后,您可以对此进行解构。这是一个示例:

const candles = [{
  open: 1,
  high: 2,
  low: 0.5,
  close: 1.5,
  volume: 200
}, {
  open: 2,
  high: 3,
  low: 0.6,
  close: 1.4,
  volume: 300
}];

const reduction = candles.reduce((acc, candle) => {
  for (let key in candle) {
    if (!(key in acc)) {
      acc[key] = [];
    }

    acc[key].push(candle[key]);
  }

  return acc;
}, {});

console.log(reduction);
// { open: [ 1, 2 ],
//   high: [ 2, 3 ],
//   low: [ 0.5, 0.6 ],
//   close: [ 1.5, 1.4 ],
//   volume: [ 200, 300 ] }

const {open, high, low, close, volume} = reduction;

console.log(open, high, low, close, volume);
// [ 1, 2 ] [ 2, 3 ] [ 0.5, 0.6 ] [ 1.5, 1.4 ] [ 200, 300 ]

答案 3 :(得分:0)

尽管 ma​​p 功能强大且有用,但对于您的示例来说,它并不是最有效的策略。

最简单的方法是根本不使用地图。如果您真的想要单行解决方案,请尝试使用解构

let candles = [{
  open: 1,
  high: 2,
  low: 0.5,
  close: 1.5,
  volume: 200
}];

[{open, high, low, close, volume}] = candles

你只需要一个简单的单线:

console.log(open, high, low, close, volume)  // 1 2 0.5 1.5 200

答案 4 :(得分:-1)

<块引用>

数组映射解构

简单的技巧: [{id:1, name:'awadhesh'}].map(({id, name}) => id + '---' + name);

let candles = [{
 open: 1,
 high: 2,
 low: 0.5,
 close: 1.5,
 volume: 200
}];
let open = candles.map(({open}) => open);
let high = candles.map(({high}) => high);
let low = candles.map(({low}) => low);
let close = candles.map(({close}) => close);
let volume = candles.map(({volume}) => volume);

console.log(open, high, low, close, volume);

日志打印 = [1] [2] [0.5] [1.5] [200]