0

I have

const a = {name: 'john', lastname: 'doe', age: '50'}

and I want to generate a new object only with name and lastname. is there any fancy ES6 wait to do it?

expected:

const b = {name: 'john', lastname: 'doe'}
handsome
  • 1,778
  • 2
  • 25
  • 48

1 Answers1

0

Use the rest operator while destructuring, assign age to a const and the spread the remaining properties with the rest operator.

const a = {name: 'john', lastname: 'doe', age: '50'};

const { age, ...b } = a;

console.log(b);

Edit: some people don't like the need to assign age so I will create a function.

const a = {name: 'john', lastname: 'doe', age: '50'};

const excludePropertys = (obj, ...props) => Object.keys(obj)
  .filter(k => !props.includes(k))
  .reduce((result, key) => {
    result[key] = obj[key];
    return result;
  }, {});

const b = excludePropertys(a, 'age');

console.log(b);

or if you want an include rather than exclude

const a = {name: 'john', lastname: 'doe', age: '50'};

const includePropertys = (obj, ...props) => props.reduce((result, key) => {
  result[key] = obj[key];
  return result;
}, {});

const b = includePropertys(a, 'name', 'lastname');

console.log(b);
Adrian Brand
  • 15,308
  • 3
  • 24
  • 46
  • 1
    What if we didn't want to use the variable `age`? This would cause linter warnings/errors and is not great practice *however* it is a very smart solution. – Nate Levin Sep 09 '20 at 20:51
  • 1
    Whilst this works, I feel like the solution should how to *include* name and last name, rather than *exclude* age (and any other properties that could be added in the future) – andy mccullough Sep 09 '20 at 20:52
  • It would only cause a problem if you need the variable name `age` in your closure. You definitely would not want to pollute a long living closure with heaps of orphan variables but in a small function it is fine. – Adrian Brand Sep 09 '20 at 21:03
  • I made a function for people who do not want to assign age. Whether you include or exclude depends on how many properties you are working with. If you have an object with 20 properties and you want to exclude two or three you want to say what to exclude. – Adrian Brand Sep 09 '20 at 21:05