首页 > 解决方案 > 将一个 JS 对象转换为另一个

问题描述

我有这样的 JS 对象。大数字是预先排序的日期时间:

{
   "param1" : [
      [1607558636000, 937.85],
      [1607561924000, 937.6],
      [1607610353000, 939.02],
      [1607610508000, 939.04],
   ],
   "param2" : [
      [1607558636000, 20.62],
      [1607561924000, 16.35],
      [1607610353000, 19.17],
      [1607610608000, 22.01],
   ],
}

并想让它看起来像这样:

{
    1607558636000 : {
      "param1" : 937.85,
      "param2" : 20.62
    },
    1607561924000 : {
      "param1" : 937.6,
      "param2" : 16.35
    },
    1607558636000 : {
      "param1" : 937.85,
      "param2" : 20.62
    },
    1607610508000 : {
      "param1" : 939.04,
      "param2" : null // no value for this parameter in this datetime
    },
    1607610608000 : {
      "param1" : null, // no value for this parameter in this datetime
      "param2" : 22.01
    },
},

想不通。一整天都在循环循环中的代码中卡住,等等......

标签: javascriptobject

解决方案


您首先需要遍历输入数据中的键,这将是输出数据对象中的键,然后遍历其中的每个值以构建您的输出对象。

这是一个javascript实现。

/*
 * Create an object to hold our output data.
 */
const resultSet = {};

/**
 * Loop over each of the keys from the input, eg.
 * 'param1', 'param2', etc.
 */ 
Object.entries(inputSet).map(([param, value]) => {
  /**
   * Loop over the values for the current parameter. 
   * dataKey is some key like `1607558636000`, and 
   * value is the value for that key and parameter, 
   * eg. 939.02
   */
  value.forEach(([dataKey, value]) => {
    /**
     * If the output data already has an entry with the 
     * given data key, create a new parameter with the
     * current param name and assign the value
     */
    if (resultSet[dataKey]) {
      resultSet[dataKey][param] = value;
    /**
     * If no such key exists, create a new object and 
     * add it to the output data.
     */
    } else {
      resultSet[dataKey] = { [param]: value };
    }
  });
});

console.log(resultSet);

推荐阅读