我有以下结构:
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中没有“重新命名”属性这样的操作。
您将需要删除不再希望保留的属性:
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)