简体   繁体   English

如何 Map 这个对象数组从每个产品项目中获取新的地理数组?

[英]How to Map this Array of objects to get a new array of geos from each products items?

I need to get a new array from this products object, of all the geos inside itmes property.我需要从该产品 object 中获取一个新数组,其中包含 itmes 属性中的所有地理信息。 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}]}]}

Here is a solution using Array.prototype.flatMap and Array.prototype.map :这是使用Array.prototype.flatMapArray.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 assuming that your source object contains more than one item in the products array, so I added one for the example.我假设您的源 object 在products数组中包含多个项目,因此我添加了一个作为示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM