[英]Merging javascript nested array of objects with parent objects in the following form in javascript?
I have an object with one of the property storing array of objects I wanted to create new object in the following form,我有一个 object,其中一个属性存储对象数组我想以以下形式创建新的 object,
{
customerEmailID: 'customer@test.com',
devices: [
{
deviceName: 'Desktop',
deviceType: 'ZENW42NLPC9861',
},
{
deviceName: 'Mobile',
deviceType: 'ZENW42NLPC9862',
},
{
deviceName: 'Laptop',
deviceType: 'ZENW42NLPC9863',
}
]
}
Expected output is,预期 output 是,
{
customerEmailID: 'customer@test.com',
deviceName1: 'Desktop',
deviceType1: 'ZENW42NLPC9861',
deviceName2: 'Mobile',
deviceType2: 'ZENW42NLPC9862',
deviceName3: 'Laptop',
deviceType3: 'ZENW42NLPC9863',
}
I wanted to create a unique column name after merge with respective parent properties.我想在与各自的父属性合并后创建一个唯一的列名。
You can loop
through array with forEach
and add properties
as shown below.您可以
forEach
loop
数组并添加properties
,如下所示。
let obj = { customerEmailID: 'customer@test.com', devices: [{ deviceName: 'Desktop', deviceType: 'ZENW42NLPC9861', }, { deviceName: 'Mobile', deviceType: 'ZENW42NLPC9862', }, { deviceName: 'Laptop', deviceType: 'ZENW42NLPC9863', } ] }; let result = { customerEmailID: obj.customerEmailID }; obj.devices.forEach((x, i) => { result["deviceName" + (i + 1).toString()] = x.deviceName; result["deviceType" + (i + 1).toString()] = x.deviceType; }); console.log(result);
You can use reduce for create new structure:您可以使用 reduce 来创建新结构:
const data = { customerEmailID: 'customer@test.com', devices: [ { deviceName: 'Desktop', deviceType: 'ZENW42NLPC9861', }, { deviceName: 'Mobile', deviceType: 'ZENW42NLPC9862', }, { deviceName: 'Laptop', deviceType: 'ZENW42NLPC9863', } ] } const newData = data.devices.reduce((acc, rec, index) => { return {...acc, [`deviceName${index+1}`]: rec.deviceName, [`deviceType${index+1}`]: rec.deviceType} }, { customerEmailID: data.customerEmailID }) console.log(newData)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.