javascript - 在 JS 中将 JSON 处理成新格式
问题描述
我目前使用此代码将我的 json 重新格式化为我想要的格式:
let input = {
"Apples": {
"Apples_pos1": 501.82,
"Apples_pos2": 502.61,
"Apples_pos3": 502.61,
"Apples": 502.16,
}
};
let output = Object.keys(input).reduce((acc, outerKey) => {
for (let [key, value] of Object.entries(input[outerKey])) {
acc.push([outerKey, value, key.split('_')[1] || key]);
}
return acc;
}, []);
console.log(output);
[
[
"Apples",
501.82,
"pos1"
],
[
"Apples",
502.61,
"pos2"
],
[
"Apples",
502.61,
"pos3"
],
[
"Apples",
502.16,
"Apples"
]
]
如果我的输入看起来像这样:
let second_input = {
"Apples": {
"11-26-19": {
"Apples_pos1": 501.82,
"Apples_pos2": 502.61,
"Apples_pos3": 502.61,
"Apples": 502.16,
}
}
};
这是我想要的输出:
[
[
"Apples",
501.82,
"pos1",
"11-26-19"
],
[
"Apples",
502.61,
"pos2",
"11-26-19"
],
[
"Apples",
502.61,
"pos3",
"11-26-19"
],
[
"Apples",
502.16,
"Apples",
"11-26-19"
]
]
我怎样才能编辑我的旧代码以产生所需的输出?
谢谢。
解决方案
我尝试完成这项任务,只是稍微修改了脚本:
let input = {
"Apples": {
"11-26-19": {
"Apples_pos1": 501.82,
"Apples_pos2": 502.61,
"Apples_pos3": 502.61,
"Apples": 502.16,
}
}
};
let output = Object.keys(input).reduce((acc, outerKey) => {
Object.entries(input[outerKey]).forEach(([date, item]) => {
for (let [key, value] of Object.entries(item)) {
acc.push([outerKey, value, key.split('_')[1] || key, date]);
}
});
return acc;
}, []);
console.log(output);
输出:
[
[
"Apples",
501.82,
"pos1",
"11-26-19"
],
[
"Apples",
502.61,
"pos2",
"11-26-19"
],
[
"Apples",
502.61,
"pos3",
"11-26-19"
],
[
"Apples",
502.16,
"Apples",
"11-26-19"
]
]
推荐阅读
- .net - GetManifestResourceNames:某些资源未嵌入(未授权?)
- python - 在熊猫数据框中将列中的值从十六进制转换为二进制
- python-3.x - 将 numpy 数组附加到文本文件中
- dart - 如何从 DART 访问 java-script 类中的方法和属性
- amazon-dynamodb - 在 AWS Appsync 中获取计数属性
- php - json Twitter Search API Php 中的空值
- sql - 通过 SQL 连接抓取类似数组的数据以形成完整的对象
- c# - WebAPI 500 内部服务器错误,未调用 api 方法
- java - Debian execute springboot app as service: service not found
- c++ - 如何打印 V8 解释器机器代码?