重命名对象数组中的对象属性

Renaming object properties in an array of objects

我有以下结构:

const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        }
    ]
};

我想将 InvoiceNumber 的所有实例重命名为 CreditNoteNumber 以提供以下内容:

const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        }
    ]
};

我已经尝试过各种方法,例如:

var changed = data.invoices.map(function(item) {
    return {
        ...data.invoices,
        CreditNoteNumber: item.InvoiceNumber
    };
});

然而,点差将 CreditNoteNumber 推到对象之外。

JavaScript中没有"renaming"a属性这样的操作。

您将需要删除您不想再保留的 属性:

const data = {
  invoices: [
    {
      Date: "2018-12-18T00:00:00.000Z",
      InvoiceNumber: "59"
    },
    {
      Date: "2018-12-18T00:00:00.000Z",
      InvoiceNumber: "59"
    }
  ]
};

const changed = data.invoices.map(item => {
  const obj = {
    ...item,
    CreditNoteNumber: item.InvoiceNumber
  };
  delete obj.InvoiceNumber
  return obj
});

console.log(changed)

只需使用解构和重命名

const data = {
  invoices: [
    {
      Date: "2018-12-18T00:00:00.000Z",
      InvoiceNumber: "59"
    },
    {
      Date: "2018-12-18T00:00:00.000Z",
      InvoiceNumber: "59"
    }
  ]
};

var changed = data.invoices.map(
  ({ Date, InvoiceNumber: CreditNoteNumber }) => ({ Date, CreditNoteNumber })
);

console.log(changed);

var changed = data.invoices.map(function(item) {
  return {
    Date: item.Date,
    CreditNoteNumber: item.InvoiceNumber
  };
});

您可以将函数 map 与函数 Object.assign 一起使用,如下所示:

以下方法不会改变原始对象

const data = {invoices: [{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"},{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"}]},
      result = data.invoices.map(({InvoiceNumber: CreditNoteNumber, ...items}) => Object.assign({}, items, {CreditNoteNumber}));

console.log(result);

如果你想改变原始对象,你可以使用 forEach 代替:

const data = {invoices: [{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"},{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"}]};

data.invoices.forEach((item) => {
  item.CreditNoteNumber = item.InvoiceNumber;
  delete item.InvoiceNumber;
});

console.log(data);

最好的选择是使用 属性 item.CreditNoteNumber 创建一个新对象 并使用 for each 循环迭代并将值重新分配给新对象。

创建新对象后,将新对象分配给原始对象 data.invoices.

const data = {invoices: [{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"},{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"}]};

var newInvoices = [];

data.invoices.forEach((item) => {
 let invoice = {};
     invoice.Date = item.Date;
     invoice.CreditNoteNumber = item.InvoiceNumber;

  newInvoice.push(invoice);
});

data.invoices = newInvoices;

console.log(data.invoices);