const payload = [
{
ControlType: 'Label',
Property: 'FirstName'
},
{
ControlType: 'DateTime',
Property: 'CreatedOn'
},
{
ControlType: 'Label',
Property: 'Price'
},
{
ControlType: 'Label',
Property: 'SubTotal'
},
{
ControlType: 'Label',
Property: 'Total'
}
];
const object1 = {
ContactId: null,
ContactName: null,
CreatedOn: '05-06-2020 12:37 PM',
CustId: '4069241-BR02',
CustName: 'ABC',
FirstName: 'Test',
LastName: 'Test',
SurName : 'Test',
Total:500,
Price: 200,
SubTotal:400,
Tax:100,
Qty : 2
};
//我需要下面的结果
const newResult = [
{
FirstName: 'Test',
ControlType: 'Label'
},
{
CreatedOn: '05-06-2020 12:37 PM',
ControlType: 'DateTime'
},
{
Price: 200,
ControlType: 'Label'
},
{
SubTotal: 400,
ControlType: 'Label'
},
{
Total: 500,
ControlType: 'Label'
}
];
答案 0 :(得分:0)
您需要遍历数组的项,为每个项添加object1中找到的Property中键的值,然后删除Property键:
payload.map(function(item){
item[item.Property] = object1[item.Property];
delete item["Property"];
return item;
})
答案 1 :(得分:0)
您可以map
:
var payload = [ { ControlType: 'Label', Property: 'FirstName' }, { ControlType: 'DateTime', Property: 'CreatedOn' }, { ControlType: 'Label', Property: 'Price' }, { ControlType: 'Label', Property: 'SubTotal' }, { ControlType: 'Label', Property: 'Total' }];
var object1 = { ContactId: null, ContactName: null, CreatedOn: '05-06-2020 12:37 PM', CustId: '4069241-BR02', CustName: 'ABC', FirstName: 'Test', LastName: 'Test', SurName : 'Test', Total:500, Price: 200, SubTotal:400, Tax:100, Qty : 2};
var result = payload.map(({Property, ...rest})=>({[Property]:object1[Property], ...rest}));
console.log(result);
答案 2 :(得分:0)
使用map
并进行销毁
const convert = (arr, obj) =>
arr.map(({ ControlType, Property }) => ({
[Property]: obj[Property],
ControlType,
}));
const payload = [
{
ControlType: "Label",
Property: "FirstName",
},
{
ControlType: "DateTime",
Property: "CreatedOn",
},
{
ControlType: "Label",
Property: "Price",
},
{
ControlType: "Label",
Property: "SubTotal",
},
{
ControlType: "Label",
Property: "Total",
},
];
const object1 = {
ContactId: null,
ContactName: null,
CreatedOn: "05-06-2020 12:37 PM",
CustId: "4069241-BR02",
CustName: "ABC",
FirstName: "Test",
LastName: "Test",
SurName: "Test",
Total: 500,
Price: 200,
SubTotal: 400,
Tax: 100,
Qty: 2,
};
console.log(convert(payload, object1));