在转换日期时,从数组到带有装饰键的对象

时间:2018-04-21 12:56:03

标签: javascript object

我正在尝试将这种数组转换为对象,同时形成日期以便能够将其与图表一起使用。

这是我到目前为止所做的一段摘录

arr=[1524314460000,0.067872,0.067876,0.067876,0.06785,0.41500986]
var obj = {...arr}
const newKeys = {0: new Date("time"), 1: "open" , 2:"low",3:"high",4:"close",5:"volume" };
function renameKeys(obj, newKeys) {
  const keyValues = Object.keys(obj).map(key => {
    const newKey = newKeys[key] || key;
    return { [newKey]: obj[key] };
  });
  return Object.assign({}, ...keyValues);
}
const renamedObj = renameKeys(obj, newKeys);
console.log(renamedObj)

正如您所见,我能够将其转换为对象,但我无法使用new Date()来转换时间,任何关于如何处理任务的想法都可以看到我得到invalid date

谢谢

3 个答案:

答案 0 :(得分:1)

new Date()移除newKeys,因为您需要time键值的日期。只需在map中添加一个条件,该条件将检查属性是否为time。如果是,请将其更改为new Date(obj[key])

的日期



arr=[1524314460000,0.067872,0.067876,0.067876,0.06785,0.41500986]
var obj = {...arr}
const newKeys = {0: "time", 1: "open" , 2:"low",3:"high",4:"close",5:"volume" };
function renameKeys(obj, newKeys) {
  const keyValues = Object.keys(obj).map(key => {
    if(newKeys[key] === 'time'){
      obj[key] = new Date(obj[key]);
    }
    const newKey = newKeys[key] || key;
    return { [newKey]: obj[key] };
  });
  return Object.assign({}, ...keyValues);
}
const renamedObj = renameKeys(obj, newKeys);
console.log(renamedObj)




答案 1 :(得分:1)

您也可以使用Arrayreduce()直接使用map转换为对象,以获得所需的结果。

<强>样本

&#13;
&#13;
const arr = [1524314460000, 0.067872, 0.067876, 0.067876, 0.06785, 0.41500986],
 newKeys = {
  0: 'time',
  1: "open",
  2: "low",
  3: "high",
  4: "close",
  5: "volume"
};

function renameKeys(arr, newKeys) {
 return arr.reduce((r,v,i)=>{
	i = newKeys[i];
	r[i]= i == 'time'? new Date(v):v;
	return r;
  },{});
}
console.log(renameKeys(arr, newKeys))
&#13;
.as-console-wrapper {  max-height: 100% !important;  top: 0;}
&#13;
&#13;
&#13;

答案 2 :(得分:1)

似乎只是使用数组索引就足够了:

&#13;
&#13;
  Error:(22, 19) java: illegal character: '\u00bc'
  Error:(22, 17) java: not a statement
  Error:(63, 24) java: illegal character: '\u00bc'
  Error:(63, 25) java: invalid method declaration; return type required
&#13;
&#13;
&#13;