Moh*_*eer 5 javascript arrays json object
我的阵列:
[
{
name: 'test1',
state: 'OK',
status: true,
pending: 33,
approved: 0,
active: 0,
inactive: 33
},
{
name: 'test3',
state: 'OK',
status: true,
pending: 33,
approved: 0,
active: 0,
inactive: 33
},
{
name: 'test4',
state: 'OK',
status: true
}
]
Run Code Online (Sandbox Code Playgroud)
如果对象中不存在“待定”、“已批准”、“活动”、“非活动”键,我需要这样的输出:
预期输出:
[
{
name: 'test1',
state: 'OK',
status: true,
pending: 33,
approved: 0,
active: 0,
inactive: 33
},
{
name: 'test3',
state: 'OK',
status: true,
pending: 33,
approved: 0,
active: 0,
inactive: 33
},
{
name: 'test4',
state: 'OK',
status: true,
pending: 0,
approved: 0,
active: 0,
inactive: 0
}
]
Run Code Online (Sandbox Code Playgroud)
这该怎么做?
我尝试使用地图,但我不知道如何设置条件。
我想将值设置为零。
您可以使用Array.map()和使用属性数组,迭代属性数组并检查每个对象是否存在该属性,如果不存在则只需添加该属性并将其值指定为 0。
let arr = [ { name: 'test1', state: 'OK', status: true, pending: 33, approved: 0, active: 0, inactive: 33 }, { name: 'test3', state: 'OK', status: true, pending: 33, approved: 0, active: 0, inactive: 33 }, { name: 'test4', state: 'OK', status: true } ];
let props = ['active','inactive', 'approved', 'pending'];
let result = arr.map(a =>{
props.forEach(prop=> a[prop] = a[prop] || 0);
return a;
});
console.log(result);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1016 次 |
| 最近记录: |