Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming object properties in an array of objects

I have the following structure:

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

I am wanting to re-name all instances of InvoiceNumber to CreditNoteNumber to give me the following:

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

I have tried various things like the following for example:

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

However the spread pushes CreditNoteNumber outside the object.

like image 232
Jim Dover Avatar asked Nov 30 '22 13:11

Jim Dover


2 Answers

Just use destructure and rename

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);
like image 183
Siva K V Avatar answered Dec 06 '22 14:12

Siva K V


There is no such operation as "renaming" a property in JavaScript.

You will need to delete the property you no longer wish to keep:

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)
like image 40
sdgluck Avatar answered Dec 06 '22 14:12

sdgluck