How to Destructure Onto an Existing Object? (JavaScript Es6)

Is it possible to destructure onto an existing object? (Javascript ES6)

While ugly and a bit repetitive, you can do

({x: oof.x, y: oof.y} = foo);

which will read the two values of the foo object, and write them to their respective locations on the oof object.

Personally I'd still rather read

oof.x = foo.x;
oof.y = foo.y;

or

['x', 'y'].forEach(prop => oof[prop] = foo[prop]);

though.

Is there a way to destructure an object into a new object in es6?

You could use delete:

const newPayload = { ...payload };

delete newPayload.cat

Or:

const { cat, ...newPayload } = payload;

Lodash also has omit():

const newPayload = _.omit(payload, ['cat']);

ES6 - Possible to destructure from object into another object property?

You're just missing brackets () around the statement.

const config = {};const source = { hello: "hello", world: "world", another: "lorem", onemore: "ipsum" };({hello: config.foo, world: config.bar} = source);console.log(config);

Javascript (es6) possible to destructure and return on a single line?

Destructure the callback parameters, and return an object:

const itemList = json.map(({ id, title }) => ({ id, title }))

Javascript destructuring to populate existing object

You are correct, you can do this:

Object.assign($scope, email);

However that is not immutable, you are actually altering the $scope object (which is fine in your case). If you want an immutable operation do this:

$scope = Object.assign({}, $scope, email);

That will return a brand new object.

Also, if you have the Object Rest Spread feature turned on in your transpiler, then you can do this:

$scope = { ...$scope, ...email };

This is also immutable and uses Object.assign behind the scenes.

ES6 Destructuring with this inside a class

You need to have the props in your class and destruct your tuple into them:

class MyClass {
a: number;
b: number;
c: number;

constructor(tuple: ReadonlyArray<number>) {
[this.a, this.b, this.c] = tuple;
}
}

Is it possible to destructure an object into existing variables?

here it can be done like this.

const complexPoint = {x: 1, y: 2, z: 3};const simplePoint = ({x, y}) => ({x, y});
const point = simplePoint(complexPoint);
console.log(point);

ES6 destructuring two objects with same property name

Yup, it looks like you can label/reassign the parameters: {before<colon>after}

var section = { name: 'foo', tables: [] };var field = { name: "bar", properties: {} };
function something({ name: sectionName }, { name: fieldName }) { console.log(sectionName, fieldName);}
something(section, field);

Destructure object and assign to another object in one line

You could probably try something like this:

({firstName: person.fistName, lastName: person.lastName} = getNames());

You would need person defined as an object beforehand.



Related Topics



Leave a reply



Submit