在Ruby中对JSON分层数据进行排序

时间:2018-10-09 19:00:53

标签: ruby-on-rails ruby tree treeview hierarchical-data

这是分层数据集。

data = [
    {
        name: "Project success",
        owner_name: "Nusaiba S.",
        created_at_in_sec: 1539089917,
        children: [
            {
                name: "Develop MVP",
                parent_name: "Project success",
                owner_name: "Nusaiba S.",
                created_at_in_sec: 1539105107,
                children: [
                    {
                        name: "Requirement Analysis",
                        parent_name: "Develop MVP",
                        owner_name: "Nusaiba S.",
                        created_at_in_sec: 1539105117
                    },
                    {
                        name: "New Feature Implement",
                        parent_name: "Develop MVP",
                        owner_name: "Nusaiba S.",
                        created_at_in_sec: 1539105119
                    }
                ]
            },
            {
                name: "Added Task to Jira",
                parent_name: "Project success",
                owner_name: "Nusaiba S.",
                created_at_in_sec: 1539090003
            },
            {
                name: "Meeting with Client",
                parent_name: "Project success",
                owner_name: "Jawad S.",
                created_at_in_sec: 1539104779

            }
        ]
    }
]

我想按以下要求对分层数据进行排序-

  • 排序应按升序或降序
  • 每个子级别都需要排序
  • 排序应使用特定的键

1 个答案:

答案 0 :(得分:-1)

我递归地编写了一种具有整个层次结构数据的方法-

require 'json'

def sort_tree_array(data, attr, asc = true)
  data = data.is_a?(String) ? JSON.parse(data) : data
  sorted = data.sort_by {|elem| [elem[attr]]}
  sorted = asc ? sorted : sorted.reverse
  sorted.each{ |item| item[:children] = sort_tree_array(item[:children], attr, asc) if (item[:children].nil? ? [] : item[:children]).size > 0 }
  sorted
end


# Get the sorted array with ascending order name
p sort_tree_array(data, :name)

# Get the sorted array with descending order name
p sort_tree_array(data, :name, false)

# Get the sorted array with ascending order created_at_in_sec
p sort_tree_array(data, :created_at_in_sec)

# Get the sorted array with descending order created_at_in_sec
p sort_tree_array(data, :created_at_in_sec, false)