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

For example, if I have two objects:

var foo = { x: "bar", y: "baz" } 

and

 var oof = {} 

and I wanted to pass the values ​​of x and y from foo to oof. Is there a way to do this using es6 destructuring syntax?

maybe something like:

 oof{x,y} = foo 
+104
javascript ecmascript-6 destructuring
Apr 14 '15 at 6:37
source share
16 answers

Although ugly and a little 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 the appropriate places in the oof object.

Personally, I would still better read

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

or

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

though.

+78
Nov 16 '16 at 5:18
source share
β€” -

No, destructuring does not support member expressions in abbreviated expressions, but only simple property names at the current time. There has been talk about this on esdiscuss, but no offers will be received in ES6.

Perhaps you can use Object.assign - if you don't need all of your own properties, you can still do

 var foo = …, oof = {}; { let {x, y} = foo; Object.assign(oof, {x, y}) } 
+33
Apr 14 '15 at 7:30
source share

IMO is the easiest way to accomplish what you are looking for:

 let { prop1, prop2, prop3 } = someObject; let data = { prop1, prop2, prop3 }; // data === { prop1: someObject.prop1, ... } 

Basically, collapse in variables, and then use the abbreviated initializer value to create a new object. No need for Object.assign

I think this is the most readable way, anyway. Here you can select the exact details from someObject that you want. If you have an existing object, you just want to combine the details, do something like this:

 let { prop1, prop2, prop3 } = someObject; let data = Object.assign(otherObject, { prop1, prop2, prop3 }); // Makes a new copy, or... Object.assign(otherObject, { prop1, prop2, prop3 }); // Merges into otherObject 

Another, possibly cleaner way to write:

 let { prop1, prop2, prop3 } = someObject; let newObject = { prop1, prop2, prop3 }; // Merges your selected props into otherObject Object.assign(otherObject, newObject); 

I use this for POST requests, where I need only a few pieces of discrete data. But I agree that there must be one liner for this.

+21
Jun 23 '17 at 18:04 on
source share

In addition to Object.assign there is an object distribution syntax , which is a Stage 2 clause for ECMAScript.

 var foo = { x: "bar", y: "baz" } var oof = { z: "z" } oof = {...oof, ...foo } console.log(oof) /* result { "x": "bar", "y": "baz", "z": "z" } */ 

But to use this feature you need to use the stage-2 plugin or transform-object-rest-spread for babel. Here is the demon on babel with stage-2

+11
Sep 15 '16 at 14:33
source share

Plugin BabelJS

If you use BabelJS , now you can activate my babel-plugin-transform-object-from-destructuring ( see the npm package for installation and use ).

I had the same problem described in this thread, and for me it was very tedious when you create an object from a destructuring expression, especially when you need to rename, add or remove a property. With this plugin, supporting such scenarios becomes much easier for you.

Object Example

 let myObject = { test1: "stringTest1", test2: "stringTest2", test3: "stringTest3" }; let { test1, test3 } = myObject, myTest = { test1, test3 }; 

can be written as:

 let myTest = { test1, test3 } = myObject; 

Array Example

 let myArray = ["stringTest1", "stringTest2", "stringTest3"]; let [ test1, , test3 ] = myArray, myTest = [ test1, test3 ]; 

can be written as:

 let myTest = [ test1, , test3 ] = myArray; 
+5
Feb 05 '18 at 7:40
source share

It is quite possible. Just not in one statement.

 var foo = { x: "bar", y: "baz" }; var oof = {}; ({x: oof.x, y: oof.y} = foo); // {x: "bar", y: "baz"} 

(Note the parentheses around the statement.) But keep in mind that readability is more important than playing code :).

Source: http://exploringjs.com/es6/ch_destructuring.html#sec_assignment-targets

+4
Feb 17 '18 at 23:40
source share

You can return the destroyed object to the arrow function and use Object.assign () to assign it to a variable.

 const foo = { x: "bar", y: "baz" } const oof = Object.assign({}, () => ({ x, y } = foo)); 
+2
Apr 10 '17 at 19:25
source share

You can simply use restructuring to do this:

 const foo = {x:"a", y:"b"}; const {...oof} = foo; // {x:"a", y:"b"} 

Or combine both objects if oof matters:

 const foo = {x:"a", y:"b"}; let oof = {z:"c"} oof = Object.assign({}, oof, foo) 
+2
Oct 09 '17 at 9:09 on
source share

DRY

 var a = {a1:1, a2: 2, a3: 3}; var b = {b1:1, b2: 2, b3: 3}; const newVar = (() => ({a1, a2, b1, b2})).bind({...a, ...b}); const val = newVar(); console.log({...val}); // print: Object { a1: 1, a2: 2, b1: 1, b2: 2 } 

or

 console.log({...(() => ({a1, a2, b1, b2})).bind({...a, ...b})()}); 
+1
Jul 07 '18 at 1:56
source share

This works in chrome 53.0.2785.89

 let foo = { x: "bar", y: "baz" }; let oof = {x, y} = foo; console.log(`oof: ${JSON.stringify(oof)}); //prints oof: { "x": "bar", "y": "baz" } 
0
Sep 09 '16 at 22:02
source share

I came up with this method:

 exports.pick = function pick(src, props, dest={}) { return Object.keys(props).reduce((d,p) => { if(typeof props[p] === 'string') { d[props[p]] = src[p]; } else if(props[p]) { d[p] = src[p]; } return d; },dest); }; 

What you can use as follows:

 let cbEvents = util.pick(this.props.events, {onFocus:1,onBlur:1,onCheck:'onChange'}); let wrapEvents = util.pick(this.props.events, {onMouseEnter:1,onMouseLeave:1}); 

ie, you can choose which properties you want and put them in a new object. Unlike _.pick you can also rename them at the same time.

If you want to copy the details to an existing object, just set the dest parameter.

0
Jan 31 '17 at 19:57
source share

This is kind of a hoax, but you can do something like this ...

 const originalObject = { hello: 'nurse', meaningOfLife: 42, your: 'mom', }; const partialObject = (({ hello, your }) => { return { hello, your }; })(originalObject); console.log(partialObject); // ​​​​​{ hello: 'nurse', your: 'mom' }​​​​​ 

In practice, I think you would rarely want to use this. The following is much clearer ... but not so much fun.

 const partialObject = { hello: originalObject.hello, your: originalObject.your, }; 

Another completely different route, which includes firmware with a prototype (be careful now ...):

 if (!Object.prototype.pluck) { Object.prototype.pluck = function(...props) { return props.reduce((destObj, prop) => { destObj[prop] = this[prop]; return destObj; }, {}); } } const originalObject = { hello: 'nurse', meaningOfLife: 42, your: 'mom', }; const partialObject2 = originalObject.pluck('hello', 'your'); console.log(partialObject2); // { hello: 'nurse', your: 'mom' } 
0
Apr 05 '17 at 20:08 on
source share

This is the most readable and shortest solution that I could offer:

 let props = { isValidDate: 'yes', badProp: 'no!', }; let { isValidDate } = props; let newProps = { isValidDate }; console.log(newProps); 

It will output { isValidDate: 'yes' }

It would be nice to someday say something like let newProps = ({ isValidDate } = props) , but unfortunately this is not what ES6 supports.

0
Nov 09 '17 at 17:33
source share

This is not a beautiful way, and I do not recommend it, but it is possible, just for knowledge.

 const myObject = { name: 'foo', surname: 'bar', year: 2018 }; const newObject = ['name', 'surname'].reduce( (prev, curr) => (prev[curr] = myObject[curr], prev), {}, ); console.log(JSON.stringify(newObject)); // {"name":"foo","surname":"bar"} 
0
Sep 07 '18 at 12:09
source share

This is actually possible using parentheses.

 const foo = { bar: 1 }; let bar; ({ bar } = foo) 

Found an eslint rule of preference-annihilation

0
Dec 12 '18 at 21:38
source share

You can destroy an object assigned directly to another attribute of the object.

Working example:

 let user = {}; [user.name, user.username] = "Stack Overflow".split(' '); document.write(' 1st attr: ${user.name} <br /> 2nd attr: ${user.username}'); 

You can work with destruction using variables with the same attribute name of the object that you want to intercept, so you do not need to do:

let user = { name: 'Mike' } let { name: name } = user;

Use this method:

let user = { name: 'Mike' } let { name } = user;

In the same way, you can set new values ​​for object structures if they have the same attribute name.

Check out this working example:

 // The object to be destructed let options = { title: "Menu", width: 100, height: 200 }; // Destructing let {width: w, height: h, title} = options; // Feedback document.write(title + "<br />"); // Menu document.write(w + "<br />"); // 100 document.write(h); // 200 
0
Jul 03 '19 at 13:36
source share



All Articles