Javascript Constructor with curly {} brackets [duplicate] - javascript

This question already has answers here:
What is destructuring assignment and its uses?
(3 answers)
Closed 3 years ago.
I am new to javascript. I am looking at pre-written code. I do not understand what is in the curly brackets:
{constructor({parts, tools, database})
class MyMenu {
constructor({parts, tools, database})
{
...
this.database = database;
this.tools = this._myTools(tools);
this.parts = this._myParts(parts);
..
}
some code here
functions()
...
...
}

This is called destructuring. e.g.
const obj = { a: 1, b: 2 };
// you can get value of a using destructuring like this
const { a } = obj;
console.log(a);
// Similarly, this applies to function arguments
//e.g.
const personData = { firstName: 'John', lastName: 'Doe', age: 20 };
class Person {
constructor ({ firstName, lastName, age }) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
const person = new Person(personData);
console.log(person.firstName);

This is object destructuring:
https://2ality.com/2015/01/es6-destructuring.html#simulating-named-parameters-in-javascript
Investigate paragraph 2.3.3.

This is destructuring, and it is an awesome feature!
o = {key1: 'value1', key2: 'value2'}
const {key2} = o
console.log(key2)
It is essentially a way of pulling elements out of objects, without having to traverse the whole object.

Related

Destructure object and assign to another object in one line [duplicate]

This question already has answers here:
Is it possible to destructure onto an existing object? (Javascript ES6)
(16 answers)
Closed 2 years ago.
Is there a way to do the following in one line?
let person = {}
const { firstName, lastName } = getNames()
//or this
//const { firstName, lastName } = await getNames()
person.firstName = firstName
person.lastName = lastName
I often do this when coding, and hoping there is a shortcut. I can not see any hints on how to do this on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment.
I was trying something like the below however, it overrides the other properties in the object.
let person = { age: 20 }
person = { ...getNames() }
I don't think this will work well with async/await functions either, as they return a promise.
let person = { age: 20 }
person = { ...await getNames() }
You could probably try something like this:
({firstName: person.fistName, lastName: person.lastName} = getNames());
You would need person defined as an object beforehand.
You can use Object.assign for this.. For example.
let person = { firstName: 'John', lastName: 'Doe', age: 67, //etc... }
let newPerson = Object.assign(person, getNames())
console.log(newPerson)
// Expected output: `{ firstName: 'newFirstName', lastName: 'newLastName', age: 67, etc... }`
You can view more on Object.assign here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Javascript spread operator [duplicate]

This question already has answers here:
Object destructuring solution for long arrays?
(2 answers)
Closed 4 years ago.
I want to get these properties from an object using es6 directly on the parameters list of the function but I don't know how to do it exactly:
function methodA(person){
var driverName = person.name,
age = person.age,
company = person.job.company;
...
}
Any tips in that direction?
Take a destructuring assignment.
function methodA(person) {
var { name: driverName, age, job: { company } } = person;
console.log(driverName, age, company);
}
methodA({ name: 'Grace', age: 49, job: { company: 'Infinity' } })

ES6 object namespacing

I came across some syntax I haven't seen before. When I deal with objects and when using React, you can simplify namespacing by doing such as
let {someProp} = prevProps
Doing this allows me to avoid writing prevProps.someProp everytime I want to use it.
What I don't understand is this syntax
let {someProp: oldData} = prevProps
console.log(someProp) will show the value of the prevPros.someProp but WHERE does oldData come from???
console.log(olddata) above this line will show undefined but console.log(oldData) underneath will show the previous props.
let {someProp: myAlias} = prevProps
This syntax allows you use an alias, for example you can use myAlias in your code, instead someProp, it is called Object destructuring
As stated in the comments by #FelixKling here is the official reference.
Example from provided link:
let o = {p: 42, q: true};
let {p: foo, q: bar} = o;
console.log(foo); // 42
console.log(bar); // true
Yes:
let {someProp} = prevProps
is similar to this:
let someProp = prevProps.someProp;
And this:
let {someProp: oldData} = prevProps
would be similar to this:
let oldData = prevProps.someProp
Take a look at this link
Basically you are destructuring prevProps and in this case oldData will now be have the value of someProp
This syntax is one of the shiny new things in ES6 called object destructuring.
Here's an elaborate example on how you can use destructuring in different ways
const person = {
first: 'Jack',
last: 'Daniels',
address: {
city: 'Dallas',
}
};
// destructure as it is
const { first, last } = person;
// destructure with custom name
const { first: firstName, last: lastName } = person;
// destructure with default value
const { first, last, middle = 'The Boss' } = person;
// destructure with custom name and default value
const { first, last, middle: middleName = 'The Boss' } = person;
// destructure nested keys
const { first, last, address: { city } } = person;
// destructure nested keys with custom name
const { first, last, address: { city: myCity } } = person;
// destructure nested keys safely
const { first, last, address: { city } = {} } = person;
// destructure rest of the values
const { first, ...rest } = person; // => rest will have all keys but first

Destructuring assignment to costruct a new object - Is it possible? [duplicate]

This question already has answers here:
Is it possible to destructure an object and generate a new object in a single statement? [duplicate]
(2 answers)
How to get a subset of a javascript object's properties
(36 answers)
One-liner to take some properties from object in ES 6
(12 answers)
Closed 5 years ago.
Is it possible to use destructuring assignment syntax to make it possible to extract data objects into another object instead distinct variables?
Example which produce distinct variables (foo, bar):
var {p: foo, q: bar} = {p: 42, q: true};
console.log(foo); // 42
console.log(bar); // true
I would need in stead to create a new object which contains the following properties as:
var n = {
foo: 42,
bar: true
}
It is not possible. The term destructuring implies that object is destructured to variables.
A way to not pollute the scope with temporary variables is to use IIFE for destructuring:
obj = (({ foo = 'foo', bar = 'bar' }) => ({ foo, bar }))(obj);
This will assign default values and will pick only valid keys from the object.
If picking is not necessary, the cleanest recipe to do this with native JS features is ES6 Object.assign:
obj = Object.assign({ foo: 'foo', bar: 'bar' }, obj);
Or ES2018 spread:
obj = { foo: 'foo', bar: 'bar', ...obj};
It sort of is, but you'll need two steps. You can't destructure directly from an object into another object, but you can make this elegant by using ES6 object notation and wrapping it into a function.
function transformObject(object) {
const { p: foo, q: bar } = object;
const newObject = {
foo,
bar
};
return newObject;
}
You cannot do it using destructuring, but you could use a helper function like this:
function retag(newStructure, source) {
var result = {};
for (var key in newStructure) {
result[key] = source[newStructure[key]];
}
return result;
}
console.log(retag(
{ foo: 'a', bar: 'b' },
{ a: false, b: 42, c: 'unused'}
));

Nested Object destructuring [duplicate]

This question already has an answer here:
ES6 Object Destructuring Default Parameters
(1 answer)
Closed 6 years ago.
When destructuring objects, I sometimes run into the issue of not knowing whether or not keys exist, and then trying to pull values from them. This obviously errors, since they are undefined. For example:
Expecting something like this:
{ user: { name: { first: 'Trey', last: 'Hakanson' } } }
But I actually get this:
{ user: {} }
and attempting to destructure like this errors:
const { user: { name: { first: firstName, last: lastName } } } = data
is there any way to assign a default value earlier in the deconstruction? Such as assigning name = { first: 'Hello', last: 'World' } if the name key doesn't exist?
const { user: { name: { first: firstName = 'firstName', last: lastName = 'lastName' } = {} } = {} } = data
You can assign default values if the value is falsy value or undefined in your case. In javascript the default values can be assigned by using the || operator.
If the first operand is falsy (false, null, undefined, "",0) then it returns the second operand. Otherwise, it returns the first operand. This provides a convenient way to specify default values
var myDefaultName = name || { first: 'Hello', last: 'World' }

Categories

Resources