簡體   English   中英

從 Javascript 中的嵌套數組 object 中創建扁平值數組

[英]Make array of flattened out value from nested array object in Javascript

我有以下數組 object。

    let reports = [
        {
            cc: 'BEL',
            cn: 'Belgium',
            entities: [
                {
                    entityName: 'Company A',
                    address: 'some address'
                }, 
                {
                    entityName: 'Company B',
                    address: 'some address'
                }
            ]
        },
        {
            cc: 'LUX',
            cn: 'Luxembourg',
            entities: [
                {
                    entityName: 'Company C',
                    address: 'some address'
                }
            ]
        }
    ];

我想通過reports go 並創建一個只有entityName值的新數組,我該如何實現?

新數組應類似於['Company A', 'Company B', 'Company C'] 我怎樣才能做到這一點?

我嘗試這樣做: reports.map(e => e.entities.map(r => r.entityName)) 然而,這返回:

[['Company A', 'Company B'], ['Company C']]

您可以對結果使用.flat()

 let reports = [ { cc: 'BEL', cn: 'Belgium', entities: [ { entityName: 'Company A', address: 'some address' }, { entityName: 'Company B', address: 'some address' } ] }, { cc: 'LUX', cn: 'Luxembourg', entities: [ { entityName: 'Company C', address: 'some address' } ] } ]; const res = reports.map(e => e.entities.map(r => r.entityName)).flat(); console.log(res);

我會這樣做,首先是 map 個實體,然后將它們扁平化,最后將 entityNames 作為單個數組結果返回:

 let reports = [{ cc: 'BEL', cn: 'Belgium', entities: [{ entityName: 'Company A', address: 'some address' }, { entityName: 'Company B', address: 'some address' } ] }, { cc: 'LUX', cn: 'Luxembourg', entities: [{ entityName: 'Company C', address: 'some address' }] } ]; const flattenedEntities = reports.map(({entities}) => entities).flat().map(({entityName}) => entityName); console.log(flattenedEntities);

您可以簡單地通過使用for循環來獲得。

 var reports = [ { cc: 'BEL', cn: 'Belgium', entities: [ { entityName: 'Company A', address: 'some address' }, { entityName: 'Company B', address: 'some address' } ] }, { cc: 'LUX', cn: 'Luxembourg', entities: [ { entityName: 'Company C', address: 'some address' } ] } ]; var yourarray = []; for (var j = 0; j < reports.length; j++) { var reportentity = reports[j].entities; for (var i = 0; i < reportentity.length; i++) { yourarray.push(reportentity[i].entityName); } } console.log(yourarray)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM