假设我有一个像这样的数组......
const myCustomers = [
{
accounts: [
{
accountID: 1234
},
{
acountID: 2345
}
]
},
{
accounts: [
{
accountID: 3456
}
]
},
{
accounts: [
{
accountID: 4567
},
{
accountID: 5678
}
]
}
];
我基本上只是想创建一个包含所有 accountID 的数组,所以它看起来像这样......
const accountIDs = [1234, 2345, 3456, 4567, 5678];
我尝试过使用 map ,但运气不佳。
const myRes = myCustomers.map(a => a.accounts.accountID);
最佳答案
myCustomers.map(c => c.accounts).flat().map(c => c.accountID)
演示:
const myCustomers=[{accounts:[{accountID:1234},{accountID:2345}]},{accounts:[{accountID:3456}]},{accounts:[{accountID:4567},{accountID:5678}]}];
const result = myCustomers.map(c => c.accounts).flat().map(c => c.accountID);
console.log( result )
或者,使用 flatMap()
的更好方法:
myCustomers.flatMap(c => c.accounts).map(c => c.accountID)
flatMap()
方法基本上首先使用映射函数映射每个元素,然后将结果展平到一个新数组中。它与 map()
后跟 flat()
相同,但 flatMap()
通常非常有用,因为将两者合并为一个方法效率稍高。
演示:
const myCustomers=[{accounts:[{accountID:1234},{accountID:2345}]},{accounts:[{accountID:3456}]},{accounts:[{accountID:4567},{accountID:5678}]}];
const result = myCustomers.flatMap(c => c.accounts).map(c => c.accountID);
console.log( result )
关于javascript - 从数组的数组中的对象获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60744760/