colors = [
["blue","red","green"],
["yellow","red","green"],
["orange","red"]
]
elements =[
{"sun"=>"yellow"},
{"sky"=>"blue"},
{"ocean"=>"blue"},
{"pumpkin"=>"orange"}
]
如何迭代colors数组以检查对象的哈希值中是否存在值,并产生此结果?
[["sun","yellow"], ["sky","blue"], ["ocean","blue"], ["pumpkin","orange"]]
答案 0 :(得分:0)
要从对象中选择项目,请使用array#select
方法:
elements.select{|el|colors.flatten.include? el.values[0]} # => [{"sun"=>"yellow"}, {"sky"=>"blue"}, {"ocean"=>"blue"}]
让我为你打破这段代码:
elements.select
遍历您的数组flatten
只展平您的颜色数组:[['a', 'b'], 'c'].flatten
为您提供['a', 'b', 'c']
array#include? i
将返回true
醇>
然后您可以将其转换为[key, value]
数组执行
filtered_elements.map(&:to_a)
这是在数组的每个对象上调用object#to_a
方法
答案 1 :(得分:0)
我认为
private func http(request: URLRequest){
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: .main)
/*Tweaking*/
let task = session.uploadTask(with: request, from: request.httpBody!)
task.resume()
}
如果单个值是request.setValue("multipart/form-data; boundary=\(yourboundary)", forHTTPHeaderField: "Content-Type")
元素之一的元素,那么objects =[{ "sun"=>"yellow" }, { "sky"=>"blue" },
{ "ocean"=>"blue" }, { "pumpkin"=>"orange" }]
的每个元素都将被保留并转换为扁平数组,其中
objects
可以写下以下内容。
colors
请注意
colors =[["blue", "red", "green"], ["yellow", "red", "green"], ["orange", "red"]]
第二个例子(ucolors = colors.flatten.uniq
#=> ["blue", "red", "green", "yellow", "orange"]
objects.flat_map(&:to_a).select { |_,c| ucolors.include? c }
#=> [["sun", "yellow"], ["sky", "blue"], ["ocean", "blue"], ["pumpkin", "orange"]]
未更改):
objects.flat_map(&:to_a)
#=> [["sun", "yellow"], ["sky", "blue"], ["ocean", "blue"], ["pumpkin", "orange"]]