forEach转换数组,可以做到通过value能找到对应的key

原数组

const arr=[
  {
    "attribute": "color",
    "concepts": [
      "white",
      "black",
      "red",
      "blue",
      "green",
      "yellow",
      "brown",
      "gray",
      "orange"
    ]
  },
  {
    "attribute": "gender",
    "concepts": [
      "male",
      "female"
    ]
  },
]

 

反向加入数组

let newArr=[]
arr.forEach(obj => {
  newArr.push({concept:obj.attribute,name:obj.attribute})//attribute加入数组
  obj.concepts.forEach(con => {
    newArr.push({concept:con,name:obj.attribute})//每个concepts加入数组
  })
});
console.log(newArr)

结果:

 

 

这样,即可通过原来的value,找到对应的name

const value = 'male'
const keys = newArr.filter(obj => obj.concept == value)
console.log(keys[0].name)//gender
 
male对应gender

 

posted @ 2020-11-18 15:52  herry菌  阅读(75)  评论(0编辑  收藏