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.
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With