My array:
[
{
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
}
]
If the "pending", "approved", "active", "inactive" key not exists in object, i need output like this:
Expected output:
[
{
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
}
]
How to do this?
I tried with map but i dont know how to set condition.
I want to set the values into zero.
You can use Array.map()
and use an array of properties, iterate over the array of properties and check for each object if that property is present in the object or not, if it is not present than simply add the property and assign it value as 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);
You can use .forEach
to apply your condition to each object.
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
}
]
arr.forEach(obj => {for (let p of ['pending', 'approved', 'active', 'inactive']){
if (!obj.hasOwnProperty(p)){
obj[p] = 0;
}
}});
console.log(arr);
.map()
to iterate over objects of the given array by passing a callback.Object.assign()
method to create a close of the current object by passing an empty object, default object and current object as arguments. First defaults values will be copied into empty object and then Object.assign()
will copy each property from the current object in the cloned effectively overriding the default values.Below is a demo:
let data = [
{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 defaults = {
pending: 0,
approved: 0,
inactive: 0,
active: 0
};
let result = data.map(o => Object.assign({}, defaults, o));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Resources:
Array.prototype.map()
Object.assign()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With