我如何使用反应钩子构建对象数组

时间:2021-06-04 17:02:30

标签: javascript reactjs react-hooks

在一个对象中,我有一个名称、图片和位置 怎样才能把职位相同的人组合在一起,在下面突出显示职位对应的名字

例如来自 json 文件的数据


    {
    "aspirants" : [
    {
    "position": "President",
    "name": "John",
    "photo": "https://"
    },
    {
    "position": "President",
    "name": "Smith",
    "photo": "https://"
    },
    {
    "position": "secretary",
    "name": "Felicia",
    "photo": "https://"
    },
    {
    "position": "President",
    "name": "Jane",
    "photo": "https://"
    }
    ]
    }

给这样的东西

总裁

约翰和(人物照片)

史密斯和(人物照片)

秘书

Felicia 和(人物照片)

Jane 和(人物照片)

1 个答案:

答案 0 :(得分:1)

最好的方法可能是使用 Array reduce 方法。你可以做一个这样的函数:

function groupByKey(people, key) {
  return people.reduce((peopleSoFar, currentPerson) => {
    return {
      ...peopleSoFar,
      [currentPerson[key]]: [
        ...(peopleSoFar[currentPerson[key]] || []), currentPerson
      ]
    }
  }, {});
}

然后像这样调用它:

groupByKey(data.aspirants, 'position')

这会给你这个:

{
  President: [
    { position: 'President', name: 'John', photo: 'https://' },
    { position: 'President', name: 'Smith', photo: 'https://' },
    { position: 'President', name: 'Jane', photo: 'https://' }
  ],
  secretary: [ { position: 'secretary', name: 'Felicia', photo: 'https://' } ]
}