[英]Sort array of documents with nested documents lodash
我有以下帶有嵌套文檔的文檔數組。 我可以使用 lodash 庫使用嵌套文檔中的特定字段對這個數組進行排序
[{
foo: {
attrb: true,
attrb1: xxx
},
foo1: {
field1: xxx,
field2: xxxx
},
foo2: {
data: 1334,
data1: 354354
}
},
{
foo: {
attrb1: xyz
},
foo1: {
field1: xxx,
field2: xxxx
},
foo2: {
data: 1334,
data1: 354354
}
},
{
foo: {
attrb1: xzy
},
foo1: {
field1: xxx,
field2: xxxx
},
foo2: {
data: 1334,
data1: 354354
}
}]
如何使用 lodash 使用數組中文檔 foo 中的 attrb: true 字段對其進行排序
您可以使用 Lodash 的sortBy
函數:
const sorted = _.sortBy(data, 'foo.attrb');
但是你不需要 Lodash 來做到這一點。 您可以使用Array#sort
:
const data = [{ foo: { attrb: true } }, { foo: { } }, { foo: { attrb: true } }]; const sorted = data.sort((a, b) => { return !!b.foo.attrb - !!a.foo.attrb; }); console.log(sorted);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.