Reputation: 305
How do I simplify the array below
[ { uuid: '',
quantity: 3,
procurement_detail_uuid: '',
distribution_officer_uuid: '',
substore_uuid: '2343423443423' },
{ uuid: '',
quantity: 3,
procurement_detail_uuid: '',
distribution_officer_uuid: '',
substore_uuid: '676767' } ]
to
[ { quantity: 3,
substore_uuid: '2343423443423' },
{ quantity: 3,
substore_uuid: '676767' } ]
What is the fastest way reduce and filter those key?
Upvotes: 0
Views: 30
Reputation: 68433
Use a map
followed by forEach
and finally delete
arr = arr.map( function(item){
Object.keys( item ).forEach( function(key){
if ( item[key] == '' )
{
delete item[key]
}
});
return item;
})
Demo
var arr = [ { uuid: '', quantity: 3, procurement_detail_uuid: '', distribution_officer_uuid: '', substore_uuid: '2343423443423' },
{ uuid: '', quantity: 3, procurement_detail_uuid: '', distribution_officer_uuid: '', substore_uuid: '676767' } ];
arr = arr.map( function(item){ Object.keys( item ).forEach( function(key){ if ( item[key] == '' ){ delete item[key] } } ); return item; } )
console.log(arr);
Upvotes: 1
Reputation: 192527
Map the array, reduce each object's keys, and take only non empty values:
const data = [{"uuid":"","quantity":3,"procurement_detail_uuid":"","distribution_officer_uuid":"","substore_uuid":"2343423443423"},{"uuid":"","quantity":3,"procurement_detail_uuid":"","distribution_officer_uuid":"","substore_uuid":"676767"}];
const result = data.map((o) => Object.keys(o)
.reduce((r, k) => o[k] !== '' ? Object.assign(r, { [k]: o[k] }) : r, {})
);
console.log(result);
Upvotes: 1