vendredi 3 mars 2023

Retrive a specific value from json using select in ruby

I have this json value

funny = [
{
    :name=>"cf_shank_1",
    :required=>true,
    :choices=>[
        [
            "firsttttt",
            "firsttttt"
        ],
        [
            "seconddd",
            "seconddd"
        ],
        [
            "thirddd",
            "thirddd"
        ],
        [
            "fourthhh",
            "fourthhh"
        ],
        [
            "otherrrr",
            "otherrrr"
        ],
    :sections=>[
        {
            :name=>"firsttttt",
            :fields=>[
                {
                    :name=>"cf_first_kano_1",
                    :required=>false
                }
            ]
        },
        {
            :name=>"thirddd",
            :fields=>[
                {
                    :name=>"multiselect_1",
                    :required=>true
                }
            ]
        }
    ]
}]

my main goal is to find all of the names which has required=true on the basis of choice selected. and we need to fetch the value form sections. and want to store it in array.

I'm trying like this but I'm interested to know how we can modify this method or can we use some other method

value = funny[:sections].select {|x| x[:name].eql?("thirddd") }
a = value.select {|i| i[:fields][:required] }
    @mandatory_item_fields_name << a[0][:name] if a.present?
  else
    @mandatory_item_fields_name << obj[:name] if obj[:required]
  end
end

My expected answer is array values which has field name where require is true. @mandatory_item_fields_name = [ multiselect_1 ]

how we can improve the code quality here? Any help is appreciated. thanks in advance

Aucun commentaire:

Enregistrer un commentaire