javascript - 从数组的数组中的对象获取值

标签 javascript node.js mongodb

假设我有一个像这样的数组......

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);

最佳答案

您可以使用 map()flat() 来完成此操作:

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/

相关文章:

javascript - 在 DRF 中使用与模型相同的日期/时间格式。DateTimeField

javascript - react JS : Map over an array of objects to render in JSX

javascript - BitGO - 从对象数组中获取帐户和值(value)

javascript - MERN 堆栈上的数据在哪里处理?

node.js - 将 mongoose 字符串模式类型默认值设为空白并使该字段可选

javascript - 获取忽略空格的javascript字符串中的最后一个字符

javascript - 如何根据选择选项访问变量的值?

node.js - Node/Mongo 内置 Promise

node.js - $使用数组过滤数组字段

node.js - Mongoose 保存嵌入文档