首页 > 解决方案 > 更改 JSON 结构

问题描述

我需要更改 JSON 结构,但我正在努力如何做到这一点,而且我不确定是否需要创建一个新对象或者我可以只处理当前对象?无论如何,这是我要更改的 JSON:

[
    {"document_name":"invoice_document.pdf"},
    {"Invoice Number":"18021573"}
]

[
    {
       "document_name":"invoice_document.pdf",
       "Invoice Number":"18021573"
    }
]

标签: javascriptjson

解决方案


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" }"


推荐阅读