Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

如何使用es6 函数式对如下对象进行排序?

let obj = {
              "name1":{
                    "abc":{
                        "test":{
                            "variable1":[{
                                "id":"2"
                              }]
                         }
                    }
                    
               },
               "name2":{
                    "abc":{
                        "test":{
                            "variable2":[{
                                "id":"0"
                              }]
                         }
                    }
                    
               },
               "name11":{
                    "abc":{
                        "test":{
                            "variable3":[{
                                "id":"2"
                              }]
                         }
                    }
                    
               },
               "name22":{
                    "abc":{
                        "test":{
                            "variable4":[{
                                "id":"10"
                              }]
                         }
                    }
                    
               },
}

如何使用函数式按照id数字大小排序并生成一个新的数组。
新数据如下:

let newArr = [
    { "test":{"variable2":[{"id":"0"}]} },
    { "test":{"variable1":[{"id":"2"}]} },
    { "test":{"variable3":[{"id":"2"}]} },
    { "test":{"variable4":[{"id":"10"}]} }
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

假定你给的数据其中 abctest 节点是固定值名称,且 variable{1...N} 都只有一个数组且包含 id 值,则:

Object.keys(obj).map(key => {
  const abcObj = obj[key].abc;
  const abcFirstKey = Object.keys(abcObj)[0];
  const testObj = abcObj[abcFirstKey];
  const testFirstKey = Object.keys(testObj)[0];
  const variables = testObj[testFirstKey];
  
  return { 
    id: variables.reduce((p, c) => p += +c.id, 0), 
    result: {
      [ abcFirstKey ]: {
        [ testFirstKey ]: variables
      }
    }
  };
})
.sort((a, b) => a.id - b.id)
.map(item => item.result);

总之,这里存在许多变数,但大体无差,可能需要更多的逻辑上的判断,但这一点取决于你的数据格式的标准。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...