0

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?

1
  • please add a not-so-fast version. Commented Nov 28, 2017 at 11:03

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.