简体   繁体   中英

Check whether key value pair exists in every object of array

I have following json data :

{
  records:{
          data:{
              current:{
                     records:{
                        '2years':[{a:1, b:2, flag:true},
                                  {a:2, b:4},
                                  {a:3, b:5, flag:true},
                                  {a:4, b:2}]
                     }
              }
          }
  }
}

I have two objects as flag_true={} and flag_false={}

I want to iterate over '2years' array and check whether flag:true exists or not in every object.

If it exists I want to push the object from 2years array into flag_true object else it will go in flag_false.

The final result should be

{
flag_true:[{a:1, b:2, flag:true},
           {a:3, b:5, flag:true}]
flag_false:[{a:2, b:4},
            {a:4, b:2} ]
}

Note that

The key 'current' is dynamic and can be either of 'current' or 'previous'

Same with array name..It can be '3years', '4years' as well

How can I do this in javascript?

please help. thanks in advance

 function convertRecord(array) { return array.reduce((obj, el) => { obj[el.flag ? 'flag_true' : 'flag_false'].push(el); return obj; }, { flag_true: [], flag_false: [] }) } const data = { records:{ data:{ current:{ records:{ '2years':[{a:1, b:2, flag:true}, {a:2, b:4}, {a:3, b:5, flag:true}, {a:4, b:2}], '3years':[{a:1, b:2, flag:true}, {a:2, b:4}, {a:3, b:5, flag:true}, {a:4, b:2}] } } } } } for(const key in data.records.data.current.records) { data.records.data.current.records[key] = convertRecord(data.records.data.current.records[key]); } console.log(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM