如何使用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"}]} }
]
阅读 2.6k
1 个回答

假定你给的数据其中 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);

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题