wilomgfx
2/13/2018 - 4:25 PM

Delete a key value pair inside an object

const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};
const userWithoutPassword = Object.keys(user)
  .filter(key => key !== 'password')
  .map(key => ({[key]: user[key]}))
  .reduce((accumulator, current) => 
    ({...accumulator, ...current}),
    {}
  )
;
// userWithoutPassword becomes {name: 'Shivek Khurana', age: 23}

//cleaner way ?
const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};
const userWithoutPassword = (({name, age}) => ({name, age}))(user);

//better way
const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};
const userWithoutPassword = Object.keys(user)
  .reduce((acc, key) => key === ‘password’ ? 
    acc : ({ …acc, [key]: user[key] }), 
    {}
  );
  
//better way for collection of keys
const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};
const userWithoutPasswordAndAge = Object.keys(user)
  .reduce((acc, key) => ['password', 'age'].indexOf(key) > -1 ? 
    acc : ({ …acc, [key]: user[key] }), 
    {}
  );