我的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
,直到从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)
您必须分离base.storms
并按顺序输入到对象字段:
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 statics = {
mainInfo: [
'base.storms',
'base.fire',
'base.flooding',
'base.theft'
]
}
const storms = data.map(el => {
const stormsInfo = statics.mainInfo[0].split('.')
return el[stormsInfo[0]][stormsInfo[1]]
})
console.log(storms)