JavaScript:如何对嵌套数组进行分组

时间:2019-05-19 22:20:45

标签: javascript react-native underscore.js lodash

我试图在React Native中使用SectionList显示数据。我已经在下面编写了显示我要完成的工作的代码。

我希望首先将数据按date分组,然后在该日期之内按位置分组。常规的JavaScript解决方案将起作用。重要的是,它具有一个titledata键。

我的输入数据采用以下格式:

[ { game_id: 1171,
    date: '2018-11-17',
    location: 'Plaza'
   },
  { game_id: 1189,
    date: '2018-11-17',
    location: 'Field - Kickball'
   },
   { game_id: 1489,
    date: '2018-11-16',
    location: 'Field - Kickball'
   },
   { game_id: 1488,
    date: '2018-11-16',
    location: 'Field - Soccer'
   }
]

我需要从上面的数据数组获得以下输出:

data = [{
    title: "2018-11-17",
    data: [{
            title: "Field - Kickball",
            data: [{
                game_id: 1189,
                date: '2018-11-17',
                location: 'Field - Kickball'
            }]
        },
        {
            title: "Plaza",
            data: [{
                game_id: 1171,
                date: '2018-11-17',
                location: 'Plaza'
            }]
        }
    ]
    },
    {
        title: "2018-11-16",
        data: [{
                title: "Field - Kickball",
                data: [{
                    game_id: 1489,
                    date: '2018-11-16',
                    location: 'Field - Kickball'
                }]
            },
            {
                title: "Field - Soccer",
                data: [{
                    game_id: 1488,
                    date: '2018-11-16',
                    location: 'Field - Soccer'
                }]
            }
        ]
    }
]

我已经尝试过了:

const games = [data here]
var groups = _(games)
.groupBy(x => x.date)
        .map(value => {
            return _.groupBy(value, 'location')
            .map(({key, value}) => ({title: key, data: value}))
        })

        .map((value, key) => {
            return ({title: value[Object.keys(value)[0]][0].date, data: value})
        })

4 个答案:

答案 0 :(得分:3)

有几种方法可以实现,但是可以使用内置的Array#reduce()方法来实现一种不需要第三方依赖的简单方法,例如Underscore或Lodash,如下所示。

有关此解决方案的工作方式的详细信息,请参见以下代码片段中的文档:

const input =  [ { game_id: 1171, date: '2018-11-17', location: 'Plaza' }, { game_id: 1189, date: '2018-11-17', location: 'Field - Kickball' }, { game_id: 1489, date: '2018-11-16', location: 'Field - Kickball' }, { game_id: 1488, date: '2018-11-16', location: 'Field - Soccer' } ];


/* Reduce input data to required nested sub-array structure */
const data = input.reduce((result, item) => {

  /* Construct item to be inserted into sub array for this item.date
  in resulting data object */
  const resultItem = {
    title: item.location,
    data: [{
      game_id: item.game_id,
      date: item.date,
      location: item.location
    }]
  };

  /* Find existing item in result array with title that matches date */
  const resultDateList = result.find(i => i.title === item.date);

  if (resultDateList) {

    /* If matching sublist found, add constructed item to it's data array */
    resultDateList.data.push(resultItem);
  } else {

    /* If not matching sublist found, add a new one to the result for this item
    and pre-populate the data array with new item*/
    result.push({
      title: item.date,
      data: [resultItem]
    });
  }

  return result;

}, [])

console.log(data)

希望有帮助!

答案 1 :(得分:2)

您可以使用ES6且不使用破折号来做类似的事情:

let arr = [ { game_id: 1171, date: '2018-11-17', location: 'Plaza' }, { game_id: 1189, date: '2018-11-17', location: 'Field - Kickball' }, { game_id: 1489, date: '2018-11-16', location: 'Field - Kickball' }, { game_id: 1488, date: '2018-11-16', location: 'Field - Soccer' } ]

let groupByfield = (data, field) => data.reduce((r, c) => {
  let key = c[field]
  r[key] = r[key] || {title: key, data: []}
  r[key].data = [...(r[key].data || []), c]	
  return r
}, {})

let result = Object.values(groupByfield(arr, 'date'))
  .map(x => ({ 
    title: x.title, 
    data: Object.values(groupByfield(x.data, 'location'))
   })
)

console.log(result)

这个想法是创建您的自定义groupBy函数,然后将其用于您的分组。

我们正在使用two chapters of You Don't Know JSArray.reduceArray.map

答案 2 :(得分:2)

如果要使用标准解决方案,则可以首先简化为一个对象,然后返回该对象的值,然后在输出上再次进行分组:)

function groupBy( arr, prop ) {
  return Object.values( arr.reduce( ( aggregate, item ) => {
    const val = item[prop];
    if (!aggregate[val]) {
      aggregate[val] = {
        [prop]: val,
        data: []
      };
    }
    aggregate[val].data.push( item );
    return aggregate;
  }, {} ) );
}

const games = [ { game_id: 1171,
    date: '2018-11-17',
    location: 'Plaza'
   },
  { game_id: 1189,
    date: '2018-11-17',
    location: 'Field - Kickball'
   },
   { game_id: 1489,
    date: '2018-11-16',
    location: 'Field - Kickball'
   },
   { game_id: 1488,
    date: '2018-11-16',
    location: 'Field - Soccer'
   }
];

const grouped = groupBy( games, 'date' )
  .map( item => ({ ...item, data: groupBy( item.data, 'location' ) }) );
  
console.log( grouped );

请注意,我只是使用提取的道具作为分组的目标属性,如果您想使用title,只需将[prop]: val更改为'title': val,然后您可以您第二次分组小麻烦:)

答案 3 :(得分:1)

使用_.flow()生成一个函数,该函数可以按字段对数组进行分组,并将其转换为{title,data}的格式。该功能还应接受数据转换器。现在,您可以递归使用它来分组多次。

const { identity, flow, partialRight: pr, groupBy, map } = _

const groupByKey = (key, transformer = identity) => flow(
  pr(groupBy, key),
  pr(map, (data, title) => ({
    title,
    data: transformer(data)
  }))
)

const data = [{"game_id":1171,"date":"2018-11-17","location":"Plaza"},{"game_id":1189,"date":"2018-11-17","location":"Field - Kickball"},{"game_id":1489,"date":"2018-11-16","location":"Field - Kickball"},{"game_id":1488,"date":"2018-11-16","location":"Field - Soccer"}]

const result = groupByKey('date', groupByKey('location'))(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

与lodash / fp相同的想法:

const { identity, flow, groupBy, map, get } = _

const groupByKey = (key, transformer = identity) => flow(
  groupBy(key),
  map(data => ({
    title: get([0, key], data),
    data: transformer(data)
  }))
)

const data = [{"game_id":1171,"date":"2018-11-17","location":"Plaza"},{"game_id":1189,"date":"2018-11-17","location":"Field - Kickball"},{"game_id":1489,"date":"2018-11-16","location":"Field - Kickball"},{"game_id":1488,"date":"2018-11-16","location":"Field - Soccer"}]

const result = groupByKey('date', groupByKey('location'))(data)

console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>