簡體   English   中英

ES6,Lodash sortBy通過2級對象數組

[英]ES6, Lodash sortBy 2 level array of objects

無法弄清楚如何對這種結構進行排序:

[
  0: { text: 'Lorem', 'children': [ 0: { text: 'Ipsum of Lorem' } ... ] }
  ...
]

我只能按這樣的第一級排序: _.sortBy(myArray,'text')

我需要類似_.sortBy(myArray, ['text','children.text'])這顯然行不通。

我需要按children.text對每個項目進行排序。

如果您需要按children數組的第一項進行排序,則可以使用'children[0].text'

 const myArray = [ { text: 'Lorem', 'children': [{ text: 'Ipsum2' }] }, { text: 'Lorem', 'children': [{ text: 'Ipsum1' }] } ] const result = _.sortBy(myArray, ['text','children[0].text']) console.log(result) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script> 

如果需要_.flow()項進行排序,然后使用第一項,則可以使用_.flow()生成函數。 該函數首先映射每個對象並對其children對象進行排序,然后對整個數組進行排序:

 const { flow, partialRight: pr, map, sortBy } = _ const fn = flow( pr(map, o => ({ ...o, children: sortBy(o.children, 'text') })), pr(sortBy, ['text','children[0].text']) ) const myArray = [ { text: 'Lorem', 'children': [{ text: 'Ipsum2' }, { text: 'Ipsum4' }] }, { text: 'Lorem', 'children': [{ text: 'Ipsum3' }, { text: 'Ipsum1' }] } ] const result = fn(myArray) console.log(result) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script> 

和相同的想法,但與lodash / fp相同:

 const { flow, map, sortBy } = _ const fn = flow( map(o => ({ ...o, children: sortBy('text', o.children) })), sortBy(['text','children[0].text']) ) const myArray = [ { text: 'Lorem', 'children': [{ text: 'Ipsum2' }, { text: 'Ipsum4' }] }, { text: 'Lorem', 'children': [{ text: 'Ipsum3' }, { text: 'Ipsum1' }] } ] const result = fn(myArray) console.log(result) 
 <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script> 

您應該遍歷children數組。

 const myArray = [{ text: 'ZLorem', 'children': [{ text: 'Ipsum2' }, { text: 'Apsum2' }] },{ text: 'Lorem', 'children': [{ text: 'Ipsum1' }, { text: 'Zpsum1' }] }], result = _.sortBy(myArray, 'text'); result.forEach(o => { if (o.children) o.children = _.sortBy(o.children, 'text'); }); console.log(result); 
 .as-console-wrapper { min-height: 100%; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script> 

您可以使用for循環跟蹤子代並對子代數組進行排序。

_.sortBy(myArray, 'text');
for(let parent of myArray) {
    _.sortBy(parent.children, 'text');
}

該代碼應按您想要的方式執行,也可以將其創建為函數

function sortParentAndChildren(myArray, key) {
    _.sortBy(myArray, key);
    for (let parent of myArray) {
        _.sortBy(parent.children, key);
    }
}

sortParentAndChildren(myArray, "text");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM