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