首页 > 解决方案 > 循环对象数组并根据定义的静态键显示值 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

但有错误

标签: javascriptreactjs

解决方案


使用一个函数作为助手,它将遍历数据和键。

在这里,我使用它直到从数组以及从数组getData中接收节点。它将从on溢出节点并递归解析数组中的数据。dataHOMEPACKAGES.mainInfoHOMEPACKAGES.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)


推荐阅读