javascriptobject

How to get a subset of a javascript object's properties


Say I have an object:

elmo = { 
  color: 'red',
  annoying: true,
  height: 'unknown',
  meta: { one: '1', two: '2'}
};

I want to make a new object with a subset of its properties.

 // pseudo code
 subset = elmo.slice('color', 'height')

 //=> { color: 'red', height: 'unknown' }

How may I achieve this?


Solution

  • Using Object Destructuring and Property Shorthand

    const object = { a: 5, b: 6, c: 7  };
    const picked = (({ a, c }) => ({ a, c }))(object);
    
    console.log(picked); // { a: 5, c: 7 }


    From Philipp Kewisch:

    This is really just an anonymous function being called instantly. All of this can be found on the Destructuring Assignment page on MDN. Here is an expanded form

    let unwrap = ({a, c}) => ({a, c});
    
    let unwrap2 = function({a, c}) { return { a, c }; };
    
    let picked = unwrap({ a: 5, b: 6, c: 7 });
    
    let picked2 = unwrap2({a: 5, b: 6, c: 7})
    
    console.log(picked)
    console.log(picked2)