【发布时间】:2019-02-09 09:05:18
【问题描述】:
我有一些数据希望整理到表格中。数据由行数组组成,行数组依次是单元格数组,这些单元格是具有属性column_name、column_value、column_type 和column_id 的对象(如下所示)。
我想按多列对数据进行排序,例如我想按city 升序排序,然后按age 降序排序。我相信lodash's _.orberBy() 可以做到这一点,但我不知道如何在这样的嵌套数据上实现它。
虽然我怀疑 lodash 会完成这项工作,但我怀疑可能还有另一种更好的方法。
我将如何按不同的列对以下嵌套数据进行排序?
import _ from 'lodash';
const sampleData = [
[
{
column_name: 'id',
column_value: '12345',
column_type: 'string',
column_id: 'item_attributes#id',
},
{
column_name: 'age',
column_value: '32',
column_type: 'number',
column_id: 'item_attributes#age',
},
{
column_name: 'city',
column_value: 'London',
column_type: 'string',
column_id: 'item_attributes#city',
},
],
[
{
column_name: 'id',
column_value: 'abcde',
column_type: 'string',
column_id: 'item_attributes#id',
},
{
column_name: 'age',
column_value: '52',
column_type: 'number',
column_id: 'item_attributes#age',
},
{
column_name: 'city',
column_value: 'Bristol',
column_type: 'string',
column_id: 'item_attributes#city',
},
],
[
{
column_name: 'id',
column_value: 'a1b2d',
column_type: 'string',
column_id: 'item_attributes#id',
},
{
column_name: 'age',
column_value: '21',
column_type: 'number',
column_id: 'item_attributes#age',
},
{
column_name: 'city',
column_value: 'London',
column_type: 'string',
column_id: 'item_attributes#city',
},
],
];
const orderedData = _.orderBy(
sampleData,
// ?? what goes here?
// ?? what goes here?
);
// desired output
// [
// [
// {
// column_name: 'id',
// column_value: 'abcde',
// column_type: 'string',
// column_id: 'item_attributes#id',
// },
// {
// column_name: 'age',
// column_value: '52',
// column_type: 'number',
// column_id: 'item_attributes#age',
// },
// {
// column_name: 'city',
// column_value: 'Bristol',
// column_type: 'string',
// column_id: 'item_attributes#city',
// },
// ],
// [
// {
// column_name: 'id',
// column_value: '12345',
// column_type: 'string',
// column_id: 'item_attributes#id',
// },
// {
// column_name: 'age',
// column_value: '32',
// column_type: 'number',
// column_id: 'item_attributes#age',
// },
// {
// column_name: 'city',
// column_value: 'London',
// column_type: 'string',
// column_id: 'item_attributes#city',
// },
// ],
// [
// {
// column_name: 'id',
// column_value: 'a1b2d',
// column_type: 'string',
// column_id: 'item_attributes#id',
// },
// {
// column_name: 'age',
// column_value: '21',
// column_type: 'number',
// column_id: 'item_attributes#age',
// },
// {
// column_name: 'city',
// column_value: 'London',
// column_type: 'string',
// column_id: 'item_attributes#city',
// },
// ],
// ]
【问题讨论】:
标签: javascript arrays functional-programming lodash