更改JSON结构

时间:2018-08-30 22:56:19

标签: javascript json

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

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

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

1 个答案:

答案 0 :(得分:0)

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