在 ruby 中,如何重新排列具有 id 键的对象数组,将数组的新顺序作为数组?

薄荷出发

我有一个带有数组的对象,如下所示:

some_object = {
  some_array: [
    { id: "foo0" },
    { id: "foo1" },
    { id: "foo2" },
    { id: "foo3" },
  ]
}

我有另一个数组的输入,我想在其中重新排列数组

target_order = [
  { id: "foo0", new_position: 3 },
  { id: "foo3", new_position: 0 },
  { id: "foo1", new_position: 2 },
  { id: "foo2", new_position: 1 }
]

如何使用第二个target_order数组来修改第一个数组的顺序some_object[:some_array]

理查德-德根

我建议您使用sort_by自定义块来查找新数组中项目的位置。

new_array = some_object[:some_array].sort_by do |item|
  order = target_order.detect { |order| order[:id] == item[:id] }
  next unless order

  order[:new_position]
end

这将返回以下值。

=> [{:id=>"foo2"}, {:id=>"foo1"}, {:id=>"foo0"}, {:id=>"foo3"}]

进一步的考虑

也许您想在列表中为每个项目指定一个位置,而不仅仅是对它们进行排序。例如

target_order = [
  { id: "foo0", new_position: 0 },
  { id: "foo1", new_position: 2 }
]

会给

=> [{ id: "foo0" }, nil, { id: "foo1" }]

为此,您应该使用each_with_object代替sort_by

new_array = target_order.each_with_object([]) do |order, memo|
  item = some_object[:some_array].detect { |item| item[:id] == order[:id] }
  next unless item

  memo[order[:new_position]] = item
end

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章