javascript - 循环对象数组并根据定义的静态键显示值 javascript
问题描述
我的 javascript 中有一组对象,其中包含如下数据
const data = [
{
base: {
storms: {
description: "Edíficio 100.000€ | Conteúdo 50.000€ | Franquia 150€",
included: true,
__typename: "PackageValue",
},
fire: {
description: "Edíficio 100.000€ | Conteúdo 50.000€ | Sem franquia",
included: true,
__typename: "PackageValue",
},
solar: {
description: "5.000€ | Franquia 150€",
included: true,
__typename: "PackageValue",
},
__typename: "HomeBase",
},
},
{....},
{.....}
];
包含此数组中的各种对象,
所以在我的文件中,我将一些静态键定义为
export const HOMEPACKAGES = {
mainInfo : ['base.storms', ///so that when i loop over array above i can use this string to access values for eg - data[i].base.storms
'base.fire',
'base.flooding',
'base.theft'
]
}
然后为了向用户展示产品,我正在循环我的对象数组
data.map((item,index)=><div>"Some content here"</div>)
现在我的问题是,一旦我开始循环并从“数据”数组中获取我的第一项,我如何获取类似的值
item.base.storms?
我试过了
data.map((item,index)=>HOMEPACKAGES.mainInfo.map((headerKey,index)=><div>{item.headerKey.included}</div>)) //in order to get item.base.storms.included
但有错误
解决方案
使用一个函数作为助手,它将遍历数据和键。
在这里,我使用它直到从数组以及从数组getData
中接收节点。它将从on溢出节点并递归解析数组中的数据。data
HOMEPACKAGES.mainInfo
HOMEPACKAGES.mainInfo
.
data
const data = [{
base: {
storms: {
description: "Edíficio 100.000€ | Conteúdo 50.000€ | Franquia 150€",
included: true,
__typename: "PackageValue",
},
fire: {
description: "Edíficio 100.000€ | Conteúdo 50.000€ | Sem franquia",
included: true,
__typename: "PackageValue",
},
solar: {
description: "5.000€ | Franquia 150€",
included: true,
__typename: "PackageValue",
},
__typename: "HomeBase",
},
}];
const HOMEPACKAGES = {
mainInfo: ['base.storms', ///so that when i loop over array above i can use this string to access values for eg - data[i].base.storms
'base.fire',
'base.flooding',
'base.theft'
]
}
function getData(key, item) {
const keys = key.split('.');
let respData = item;
keys.forEach((node) => respData = respData[node]);
return respData;
}
const resp = data.map((item,index) => HOMEPACKAGES.mainInfo.map((headerKey,index)=>{
return getData(headerKey, item)
})) //in order to get item.base.storms.included
console.log(resp)
推荐阅读
- sql - 如何选择具有最大 id 的记录并对值求和?
- google-cloud-platform - 基于查询的参数路由 Google 负载均衡器 - IAP
- azure - 无法删除 azure free trail 中的资源组
- sql - 与并非所有列共有的多态关系
- javascript - 基于 objectd 的 n 个键的组数组
- javascript - Vue.js - 如何将道具传递给带有插槽的组件元素
- javascript - JS中同步调用函数
- android - 如何使用 OAuth 2.0 验证 Flutter 应用程序以访问 Gmail api?
- java - 为什么这段代码会给我超时错误?
- java - 为什么我会收到 ConcurrentModificationException?