javascript - 展平嵌套的 JSON 对象
问题描述
我有一个像这样的 json 对象:
const people = {
name: 'My Name',
cities: [{city: 'London', country: 'UK'},{city: 'Mumbai', country: 'IN'},{city: 'New York', country: 'US'}],
}
我想要这样的输出:即对于每个城市,我想展平数组。
[
['My Name', 'London', 'UK'],
['My Name','Mumbai', 'IN'],
['My Name','New York', 'US']
]
我已经尝试过扁平化等,但无法弄清楚如何实现这一点。有人可以帮我吗?谢谢,萨西
解决方案
这应该可以解决问题!
const people = {
name: 'My Name',
cities: [{city: 'London', country: 'UK'},{city: 'Mumbai', country: 'IN'},{city: 'New York', country: 'US'}],
}
function flattenIt(obj) {
const name = obj.name;
const cityData = obj.cities;
return cityData.map(({city, country}) => [name, city, country])
}
console.log(flattenIt(people));
推荐阅读
- .net - ASP.NET Core 数据保护跨平台加密提供程序
- user-interface - 在 Unity 中检测 UI 面板内的下拉问题
- c++ - 只需生成一个导入库 (.lib) 而不链接 DLL
- magento - Magento 订单状态更改的触发观察者不适用于 sales_order_save_after
- android - 在 Android Studio 3.2 项目上安装 SDK
- angular - 暂停/恢复计时器 Observable
- algorithm - 算法 - 根据最相似的偏好对用户进行分组
- html - CSS - 使用 (~) 兄弟运算符的替代方案
- php - 使用 txt 文件(包含字符串的大列表)搜索字谜
- matlab - 多元隐马尔可夫模型实现问题