javascript - 更改 JSON 结构
问题描述
我需要更改 JSON 结构,但我正在努力如何做到这一点,而且我不确定是否需要创建一个新对象或者我可以只处理当前对象?无论如何,这是我要更改的 JSON:
[
{"document_name":"invoice_document.pdf"},
{"Invoice Number":"18021573"}
]
至
[
{
"document_name":"invoice_document.pdf",
"Invoice Number":"18021573"
}
]
解决方案
let a = [
{"document_name":"invoice_document.pdf"},
{"Invoice Number":"18021573"}
];
// Use reduce on `a` because we know we want 1 after this is done.
// `Acc` is short for accumulator.
a = a.reduce((acc, i) => {
// Use Object.keys to get access to the key names.
Object.keys(i).map((key) => {
// Append item onto the accumulator using its key and value
// Warning: this will overwrite any existing `acc[key]` entries of the
// same `key` value.
acc[key] = i[key];
})
return acc;
// This last Object here is what we start with when reduce runs the first time.
}, {});
产量:
{
"document_name": "invoice_document.pdf",
"Invoice Number": "18021573"
}"
推荐阅读
- javascript - 导出为 .txt 文件时,缩进/对齐 JavaScript 中的每个字符串行
- css - Angular 5 自定义组件 CSS
- java - 在 Jsp 项目中嵌入 Angular 5 应用程序
- session - 在使用 htpp 和 https 的 drupal 中,未设置的会话有效一段时间无法正常工作
- google-bigquery - 在 Google Bigquery 中执行传输 - PERMISSION_DENIED:未找到具有 Google Drive 范围的 OAuth 令牌
- swift - 使用完成处理程序实现自定义函数
- javascript - 使用 vue-test-utils 时的 Vue 警告
- google-calendar-api - 谷歌日历 PHP API 时间问题
- excel - 检查输入excel在范围内是否有效
- python - asyncio.test_utils.run_briefly 究竟做了什么?