如何在 React Native 中对数组进行分组

How to group an array within React Native

我有一个名为 "directory" 的对象数组,其中包含人员及其工作的列表。问题是一个人可以担任超过 1 个角色,我想在渲染过程中将 "job" 分组在同一个 "id" 下。 这是我的数组:

"directory": 
[
    {            
      "id": 37,
      "job": "Electrician",
      "name": "Alan"
    },
    {
      "id": 32,
      "job": "Writer",
      "name": "Mark"
    },
    {
      "id": 37,
      "job": "DIY",
      "name": "Alan"
    },
    {
      "id": 134,
      "job": "Director",
      "name": "Philip"
    },
    {
      "id": 37,
      "job": "Plumber",
      "name": "Alan"
    },
    {
      "id": 85,
      "job": "Teacher",
      "name": "Oliver"
    },
]

我想要一个新数组显示为:

Alan: Electrician, Plumber, DIY
Mark: Writer
Philip: Director,
Oliver: Teacher

我不确定我应该使用嵌套 .map 还是 reduce。

感谢任何帮助。

您可以在 JS 中使用 reduce() 来解决您的问题

let directory = [
    {
        "id": 37,
        "job": "Electrician",
        "name": "Alan"
    },
    {
        "id": 32,
        "job": "Writer",
        "name": "Mark"
    },
    {
        "id": 37,
        "job": "DIY",
        "name": "Alan"
    },
    {
        "id": 134,
        "job": "Director",
        "name": "Philip"
    },
    {
        "id": 37,
        "job": "Plumber",
        "name": "Alan"
    },
    {
        "id": 85,
        "job": "Teacher",
        "name": "Oliver"
    },
]

let newDirectory = Object.values(directory.reduce((acc, item) => {
    if (!acc[item.name]) acc[item.name] = {
        name: item.name,
        job: []
    };
    acc[item.name].job.push(item.job);
    return acc;
}, {}))

console.log(newDirectory)

然后你可以使用React-Native中的SectionList来根据你的需要显示数据或者你可以试试下面的方法,

import React, { Component } from 'react';
import { Text, View } from 'react-native';

const newDirectory = [
    { name: 'Alan', job: ['Electrician', 'DIY', 'Plumber'] },
    { name: 'Mark', job: ['Writer'] },
    { name: 'Philip', job: ['Director'] },
    { name: 'Oliver', job: ['Teacher'] }
]

export default class App extends Component {
    render() {
        return (
            <View style={{ flex: 1, marginTop: 50 }}>
                {
                    newDirectory.map(item => (
                        <Text>{item.name}: {
                            item.job.map(job => (
                                <Text>{`${job}, `}</Text>
                            ))
                        }</Text>
                    ))
                }
            </View>
        );
    }
}

希望对您有所帮助。有疑问欢迎留言。