javascript - 将一个 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
},
},
想不通。一整天都在循环循环中的代码中卡住,等等......
解决方案
您首先需要遍历输入数据中的键,这将是输出数据对象中的键,然后遍历其中的每个值以构建您的输出对象。
这是一个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);
推荐阅读
- javascript - CSS在表格的列背景色和表格中的选定行中禁用了输入
- php - 在 php 中使用正则表达式在字符串之后获取括号中的内容
- ios - 如何在flutter插件中导入外部iOS框架?
- python - 是否可以通过python或任何其他语言将每日下载的文件归档到一个文件夹中
- generics - Typescript如何将属性声明为其类的通用参数T的键列表?
- r - R中的XML:在存储祖先信息的同时提取节点
- c# - 如何在 C# 中以另一个排序列表为基础对 IList 进行排序?
- r - 汇总 data.table .SD,同时按 .SDcols 之一排序
- docker - 码头工人 + 开放式移位。如何仅使用私有注册表?
- jquery - 动态创建 div 但 tinyMce 没有为动态创建的 div 加载