![](/img/trans.png)
[英]How to check if a key value pair (in an array) exists in another array?
[英]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.