我有一组具有唯一ID的对象:
[{id: 1, score: 33}, {id: 23, score: 50}, {id:512, score: 27}, ...]
我还有一组具有匹配ID的用户记录。用户记录有" name"但不是"得分":
[{id: 1, name: "Jon"}, {id: 23, name: "Tom"}, {id: 512, name: "Joey"}, ...]
如何创建包含每个ID,名称和分数的单个数组?
[{id: 1, name: "Jon", score: 33}, {id: 23, name: "Tom", score: 50}, {id: 512, name: "Joey", score: 27}, ...]
我尝试了merge
,combine
,filter
等,但还没有找到Ruby功能来实现这一目标。
答案 0 :(得分:3)
假设在:id
中有始终记录,并且来自scores
的对应scores = [{id: 1, score: 33}, {id: 23, score: 50}, {id:512, score: 27}]
users = [{id: 1, name: "Jon"}, {id: 23, name: "Tom"}, {id: 512, name: "Joey"}]
scores = scores.map { |score| score.merge(users.find { |user| user[:id] == score[:id] }) }
# => [{:id=>1, :score=>33, :name=>"Jon"}, {:id=>23, :score=>50, :name=>"Tom"}, {:id=>512, :score=>27, :name=>"Joey"}]
:
Button
希望能让你朝着正确的方向前进!
答案 1 :(得分:1)
您可以使用中间哈希。
var app = angular.module("Layout", []);
app.controller("LoadPage", function ($scope, $http, $sce) {
//Initially
$scope.templateUrl = '/Home/DefaultPage';
// To dynamically change the URL.
$scope.NewProjFn = function () {
$scope.templateUrl = '/Home/ProjectPage';
};
});
答案 2 :(得分:1)
如果在示例中scores[i][:id] = users[i][:id]
用于所有i
,并且您使用的是v1.9 +(其中维护了密钥插入顺序),则可以写:
scores.zip(users).each_with_object({}) do |(sh,uh),h|
h.update(sh).update(uh)
end
我会用这个吗?你呢?