我有2个数组,我想将它们组合在一个应该返回嵌套JSON的数组中。 第一个是清洁剂,它返回:
{
"response": [
{
"id": 1,
"first_name": "Fernando",
"last_name": "Gomez",
"avg_rating": "4.5"
}
]
}
第二个是来自客户的评论 它返回客户的名称,评论和评级:
{
"response": [
{
"id": 1,
"score": 4,
"comment": "Comment",
"first_name": "John Doe"
}
]
}
所以,我试图拉链它们并循环遍历它们。这是我的代码:
cleaners.zip(reviews).each do |cleaner, review|
if cleaner.id == review.id
test['first_name'] = cleaner.first_name
test['last_name'] = cleaner.last_name
test['rating'] = review.score
test['comment'] = review.comment
test['client_name'] = review.first_name
end
end
结果是:
{
"response": {
"first_name": "Fernando",
"last_name": "Gomez",
"rating": 4,
"comment": "Comment",
"client_name": "John Doe"
}
}
但我的结果必须嵌套,因为有些清洁工会有很多评论。它必须是这样的:
{
"response": {
"first_name": "Fernando",
"last_name": "Gomez",
"score_from_client": [
{
"rating": 4,
"comment": "Comment",
"client_name": "John Doe"
}
]
}
}
答案 0 :(得分:0)
以下是问题的答案:)
unless cleaners.nil?
cleaner_ids = []
cleaners_reviews = []
cleaners.each do |cleaner|
cleaner_review = {
id: cleaner.id,
avg_rating: cleaner.avg_rating,
first_name: cleaner.first_name,
last_name: cleaner.last_name,
ratings: []
}
cleaners_reviews << cleaner_review
cleaner_ids << cleaner.id
end
reviews = Cleaner.get_cleaner_reviews(dates, cleaner_ids)
unless reviews.empty?
i = 0
reviews.each do |review|
cleaners_reviews[i][:ratings] << review
i += i
end
end
return cleaners_review
取值