如何映射此对象数组以从每个产品项中获取新的地理数组? [英] How to Map this Array of objects to get a new array of geos from each products items?

查看:56
本文介绍了如何映射此对象数组以从每个产品项中获取新的地理数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从此产品对象中获取itmes属性内所有geos的新数组。我该怎么做?

I need to get a new array from this products object, of all the geos inside itmes property. how i can do that?

"products":[{"code":"realestate","currency":"ILS","percentage":1,"totalWorth":150000,"totalYieldPer":0,"items":[{"name":"הבית שלנו בחיפה ","currency":"NIS","geo":"ישראל","worth":150000,"portfolioPer":0.022,"yield":0,"yieldPer":0},{"name":"הבית שלנו בארהבב","currency":"USD","geo":"ארהב","worth":5261700,"portfolioPer":0.761,"yield":0,"yieldPer":0},{"name":"דירהב אירופה","currency":"NIS","geo":"אירופה","worth":5261700,"portfolioPer":0.761,"yield":0,"yieldPer":0}]}]}


推荐答案

以下是使用 Array.prototype.flatMap Array.prototype。地图

Here is a solution using Array.prototype.flatMap and Array.prototype.map:

const obj = {
    "products": [{
            "code": "realestate",
            "currency": "ILS",
            "percentage": 1,
            "totalWorth": 150000,
            "totalYieldPer": 0,
            "items": [{
                    "name": "הבית שלנו בחיפה ",
                    "currency": "NIS",
                    "geo": "ישראל",
                    "worth": 150000,
                    "portfolioPer": 0.022,
                    "yield": 0,
                    "yieldPer": 0
                }, {
                    "name": "הבית שלנו בארהבב",
                    "currency": "USD",
                    "geo": "ארהב",
                    "worth": 5261700,
                    "portfolioPer": 0.761,
                    "yield": 0,
                    "yieldPer": 0
                }, {
                    "name": "דירהב אירופה",
                    "currency": "NIS",
                    "geo": "אירופה",
                    "worth": 5261700,
                    "portfolioPer": 0.761,
                    "yield": 0,
                    "yieldPer": 0
                }
            ]
        }, {
            "items": [{ "geo": "Some other geo" }]
        }
    ]
};

const result = obj.products.flatMap(({ items }) => items).map(({ geo }) => geo);

console.log(result);

I' m假设您的源对象在产品数组中包含多个项目,因此我为示例添加了一个项目。

I'm assuming that your source object contains more than one item in the products array, so I added one for the example.

这篇关于如何映射此对象数组以从每个产品项中获取新的地理数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆