[英]Plucking objects from multi-dimensional array
Say we have the following array:假设我们有以下数组:
const admins = [
{
adminName: 'admin 1',
devices: [
{
deviceName: 'device 1',
os: 'desktop',
appVersion: 1.2.0
},
{
deviceName: 'device 2',
os: 'desktop',
appVersion: 1.4.0
}
]
},
{
adminName: 'admin 2',
devices: [
{
deviceName: 'device 1',
os: 'ios',
appVersion: 1.4.0
},
{
deviceName: 'device 2',
os: 'android',
appVersion: 1.1.0
}
]
}
]
I'm attempting to gather all the devices from various admins into a single array like so.我正在尝试将来自不同管理员的所有设备收集到一个数组中,就像这样。
const adminDevices = admins.map(admin => admin.devices);
But this returns an array that has another array in it which contains the devices.但这会返回一个数组,其中包含另一个包含设备的数组。
I have tried the following:我尝试了以下方法:
const adminDevices = admins.map((admin) => {
return admin.devices.reduce((accumulator, value) => {
return value;
}, {});
});
But this as expected only returns the first device value.但这正如预期的那样只返回第一个设备值。 Any suggestions on how I could accomplish this with any of the Array methods without having to declare an empty array or set and fill that out manually?
关于如何使用任何 Array 方法完成此操作而无需声明空数组或手动设置和填充它的任何建议?
const admins = [ { adminName: 'admin 1', devices: [ { deviceName: 'device 1', os: 'desktop', appVersion: '1.2.0' }, { deviceName: 'device 2', os: 'desktop', appVersion: '1.4.0' } ] }, { adminName: 'admin 2', devices: [ { deviceName: 'device 1', os: 'ios', appVersion: '1.4.0' }, { deviceName: 'device 2', os: 'android', appVersion: '1.1.0' } ] } ]; const adminDevices = admins.flatMap(admin => admin.devices); console.log(adminDevices)
If you are going to go ahead and flat-map the device lists, I would also try to associate the adminName
to each device
.如果您要提前转到 go 并对设备列表进行平面映射,我也会尝试将
adminName
关联到每个device
。 This way you do not lose any info when ungrouping.这样您在取消分组时就不会丢失任何信息。
const admins = [{ adminName: 'admin 1', devices: [ { deviceName: 'device 1', os: 'desktop', appVersion: '1.2.0' }, { deviceName: 'device 2', os: 'desktop', appVersion: '1.4.0' } ] }, { adminName: 'admin 2', devices: [ { deviceName: 'device 1', os: 'ios', appVersion: '1.4.0' }, { deviceName: 'device 2', os: 'android', appVersion: '1.1.0' } ] }]; const adminDevices = admins.flatMap(({ adminName, devices }) => devices.map((device) => ({ adminName, ...device }))); adminDevices.forEach(device => console.log(JSON.stringify(device)));
.as-console-wrapper { top: 0; max-height: 100%;important; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.