Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure newValue = value.value?

This is just trivia / curiosity as I stumble across this situation a number of times.

Is it possible to shorten/destructure the following types of assignments?

newValue = value.value

Naively, I tried newValue = {value} but it doesn't work, as that syntax is normally used to destructure variables from objects with the same key name.

like image 426
James Avatar asked Aug 21 '18 06:08

James


People also ask

How do you Destructure a property?

The object destructuring is a useful JavaScript feature to extract properties from objects and bind them to variables. What's better, object destructuring can extract multiple properties in one statement, can access properties from nested objects, and can set a default value if the property doesn't exist.

How do I set default value in Destructuring?

In Arrays: In Arrays, values of corresponding elements get stored in the variables. Example 1: In order to give default values in arrays when applying the destructuring concept in arrays, we need to initialize values with some value. In this way the default values will be assigned to the variables.

Can we Destructure array?

Destructuring in Arrays. To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element. const [var1, var2, ...]


2 Answers

Use this syntax to destructure and rename the property, this will get the value from object and rename it to variable newValue

var {value: newValue} = value

var value = {value: 5}

var {value: newValue} = value

console.log(newValue)
like image 142
Anurag Awasthi Avatar answered Sep 18 '22 11:09

Anurag Awasthi


You could use the object property assignment pattern [YDKJS: ES6 & Beyond] with a destructuring assignment.

var value = { value: 42 },
    { value: newValue } = value;

console.log(newValue);

If not used as expression, like with var, let or const, you need parentheses to distinguish the braces from a block statement.

var value = { value: 42 },
    newValue;

({ value: newValue } = value);

console.log(newValue);
like image 28
Nina Scholz Avatar answered Sep 19 '22 11:09

Nina Scholz