Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用lodash orderBy对具有深层嵌套属性的对象数组进行排序?_Javascript - Fatal编程技术网

Javascript 如何使用lodash orderBy对具有深层嵌套属性的对象数组进行排序?

Javascript 如何使用lodash orderBy对具有深层嵌套属性的对象数组进行排序?,javascript,Javascript,这是使用lodash中orderBy的推荐方法 const data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']); - instead of keys 有没有办法做到这一点? 我是否可以像下面这样以字符串数组形式传递键路径,而不是对象键['type','name'] 因此,预期结果将是基于深度值的排序数组 const data = _.orderBy(array_of_objects, ['type.id

这是使用lodash中orderBy的推荐方法

 const data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']); - instead of keys 
有没有办法做到这一点? 我是否可以像下面这样以字符串数组形式传递键路径,而不是对象键
['type','name']

因此,预期结果将是基于深度值的排序数组

 const data = _.orderBy(array_of_objects, ['type.id','name.entry'], ['asc', 'desc']); - instead of keys 
我这样问是因为我们可以像这样使用lodash\uz.get()访问对象的深层属性

_.get(object, 'a[0].b.c');
// => 3
因此,一定有一种方法可以通过u.orderBy()实现这一点

NB如果在vanilla js中有这样做的方法,请也提出建议

目前在我的例子中,这并不是为我传递的每个键排序
['type.id','name.entry']
只有一个键在工作

如果不可能,请建议如何基于多个深度嵌套的道具(作为字符串路径传递)对具有深度嵌套道具的数组对象进行排序接受回调,如果需要基于多个属性进行排序,则这可以是函数列表。此语法基于Lodash 4.x

// for ordering based on a single attribute
const orderedData = _.orderBy(arrayOfObject, item => item.id, ['desc']);

// for ordering based on multiple attributes
const orderedData = _.orderBy(arrayOfObject, [
  item => item.id,
  item => item.entry,
], ['desc', 'asc']);
以下示例说明了如何根据每个对象中的嵌套属性进行排序:

const items = [
  {
    id: 1,
    entry: 'a',
    nested: { val: 5 },
  },
  {
    id: 5,
    entry: 'five',
    nested: { val: 1 },
  },
  {
    id: 3,
    entry: 'three',
    nested: { val: 2 },
  },
  {
    id: 2,
    entry: 'two',
    nested: { val: 3 },
  },
  {
    id: 4,
    entry: 'four',
    nested: { val: 4 },
  },
];


const nestedValueComparator = item => _.get(item, 'nested.val');

const nestedData = _.orderBy(items, nestedValueComparator, ['asc']);

难道orderBy不接受回调吗?我不确定。你能推荐一些代码吗?有没有其他基于多个字段/键的排序方法?或者可以是组合u.get()和array.sort()??如果不支持回调,根据文档,您只需编写
\uu.orderBy(数组\u的对象,[x=>x.type.id,x=>x.name.entry],'asc','desc'])甚至可能
\uu.orderBy(数组\u对象,[['type','id',['name','entry']],['asc','desc']),但我不确定。u.sortByAll(用户,[{'key':'user','desc':true},{'key':'age'},//默认为'desc':false{'key':'gender','desc':false}//您也可以显式地这么说];