如何将数组转换为Javascript中的字典(还将列重新排序为行)?

时间:2018-12-21 14:53:47

标签: javascript data-structures javascript-objects

我有以下数组数组:

[
  [o1, c1, h1, l1 ,t1],
  [o2, c2, h2, l2, t2],
  ...
  [oN, cN, hN, lN, tN]
]

我需要将其转换为以以下方式构造的对象:

{
  open:   [o1,o2,o3,o4,o5,o6,o7,o8, ... oN],
  close:  [c1,c2,c3,c4,c5,c6,c7,c8, ... cN],
  high:   [h1,h2,h3,h4,h5,h6,h7,h8, ... hN],
  low:    [l1,l2,l3,l4,l5,l6,l7,l8, ... lN],
  time:   [t1,t2,t3,t4,t5,t6,t7,t8, ... tN]
}

所以这意味着我需要解决的另一个问题是将列重组为行。

以下是对我有用的代码:

function convertData(rawDataArray) {
  [open, close, high, low, timesignature] = [
    [],
    [],
    [],
    [],
    []
  ];
  var arrayLength = rawDataArray.length;
  for (var i = 0; i < arrayLength; i++) {
    open.push(rawDataArray[i][1])
    close.push(rawDataArray[i][2])
    high.push(rawDataArray[i][3])
    low.push(rawDataArray[i][4])
    timesignature.push(rawDataArray[i][0])
  }
  return {
  	open: open,
    close: close,
    high: high,
    low: low,
    timeSignature: timesignature
  }
}

但是,我的解决方案在我看来是个笨拙而不是优雅的解决方案。我很想学习一种更有效的方式编写代码。

3 个答案:

答案 0 :(得分:0)

let row =[
  ["o1", "c1", "h1", "l1","t1"],
  ["o2", "c2", "h2", "l2", "t2"]
]
const extractIndex = (ind,data)=> data.map(e=>e[ind]) 
const convertDataNew = (rawDataArray)=> {
  return {
    open: extractIndex(0,rawDataArray),
    close: extractIndex(1,rawDataArray),
    high: extractIndex(2,rawDataArray),
    low: extractIndex(3,rawDataArray),
    timeSignature: extractIndex(4,rawDataArray)
  }

}


console.log(convertDataNew(row))

答案 1 :(得分:0)

我以优雅的态度假设您的意思是易于阅读的代码,并不一定意味着更快的性能。这是map()派上用场的地方,因为它可以将笨拙的for循环减少到一行。

function convertData(rawDataArray) {
    return {
        open: rawDataArray.map(i=>i[0]),
        close: rawDataArray.map(i=>i[1]),
        high: rawDataArray.map(i=>i[2]),
        low: rawDataArray.map(i=>i[3]),
        timeSignature: rawDataArray.map(i=>i[4])
    }
}

答案 2 :(得分:0)

您可以获取键并将其用作属性访问器的一部分,以推送值。

h = new Date().getHours();
m = new Date().getMinutes();
isOpen: boolean;

timeNow = (this.m < 10) ? '' + this.h + 0 + this.m : '' + this.h + this.m;

openTime = parseInt(this.timeNow);


closed() {

(this.openTime >= 1450 && this.openTime <= 1830) ? this.isOpen = true : 
this.isOpen = false;
(this.openTime >= 715 && this.openTime <= 915) ? this.isOpen = true : 
this.isOpen = false;