繁体   English   中英

检查数组的每个对象中是否存在键值对

[英]Check whether key value pair exists in every object of array

我有以下 json 数据:

{
  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}]
                     }
              }
          }
  }
}

我有两个对象flag_true={}flag_false={}

我想迭代 '2years' 数组并检查flag:true是否存在于每个对象中。

如果它存在,我想将对象从 2years 数组推入 flag_true 对象,否则它将进入 flag_false。

最后的结果应该是

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

注意

键 'current' 是动态的,可以是 'current' 或 'previous'

与数组名称相同..它也可以是 '3years', '4years'

我怎样才能在 javascript 中做到这一点?

请帮忙。 提前致谢

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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