let { var} definition - what is it [duplicate] - javascript

This question already has an answer here:
Where can I get info on the object parameter syntax for JavaScript functions?
(1 answer)
Closed last year.
I saw this code on a package:
const SortableList = SortableContainer(({items}) => {
return (
<ul>
{items.map((value, index) =>
<SortableItem key={`item-${index}`} index={index} value={value} />
)}
</ul>
);
});
What is happening to items by putting curly braces around it in the function parameters?

This is destructuring assignment syntax.
As another example, the following two lines of code are equal:
const { items } = args
const items = args.items
Simply put, it is a simplified way of accessing specific field of a given variable for further use in that scope.
In your original example, it is declaring a variable items for use in the function body that is the items field of that first argument.
const SortableList = SortableContainer(({items}) => {
// do stuff with items here
is equal to
const SortableList = SortableContainer((input) => {
const items = input.items
// do stuff with items here

This question is likely a repost: What do {curly braces} around javascript variable name mean
But as an answer, it's destructuring assignment. If your object being passed in mirrors the variable being referenced, you can retrieve that specific field during assignment.

This is Destructuring Assignment.
In this example below, the variables "name", "sex" and "age" in curly braces "{}" extract the values "John", "Male" and "24" from "data" respectively:
*The variable names in curly braces "{}" must be same as the key names in "data"
const data = { name: "John", sex: "Male", age: 24 };
const { name, sex, age } = data;
console.log(name); // John
console.log(sex); // Male
console.log(age); // 24
If the variable names in curly braces "{}" are not same as the key names in "data", the values of "undefined" are assigned:
const data = { name: "John", sex: "Male", age: 24 };
const { myName, mySex, age } = data;
console.log(myName); // undefined
console.log(mySex); // undefined
console.log(age); // 24
The order of the variables in curly braces "{}" doesn't matter:
const data = { name: "John", sex: "Male", age: 24 };
const { age, sex, name } = data;
console.log(name); // John
console.log(sex); // Male
console.log(age); // 24
You can rename the variables in curly braces "{}":
const data = { name: "John", sex: "Male", age: 24 };
const { name: firstName, sex: gender, age } = data;
console.log(firstName); // John
console.log(gender); // Male
console.log(age); // 24
After renaming the variables in curly braces "{}", the original variables don't work and give error:
const data = { name: "John", sex: "Male", age: 24 };
const { name: firstName, sex: gender, age } = data;
console.log(name);
console.log(sex);
console.log(age);

Related

Refactoring a destructuring into an object destructuring

I am refactoring my code, which involves converting a big list of let statements into an object called personDetails:
personDetails = {
firstName: '',
lastName: '',
zipcode: 'xyz',
age: 20,
gender: 'm'
}
Currently, I am destructuring the values returned from my array like this:
[firstName, lastName] = getNames(zipcode, age, gender)
This works fine. But now that I am switching to an object, how do I update that object with the returned values? I will be passing in the object as an argument like this:
getNames(personDetails)
Do I have to do something like this?
personDetails = getNames(personDetails)
The called function might look something like this (abbreviated):
const getNames(personDetails) => {
personDetails.firstname = 'Jack'
personDetails.lastName = 'Jones'
}
1) Your arrow function had a typo, you must declare it with an = before the argument, like this:
const getNames = (personDetails) => { // Correct
const getNames(personDetails) => { // Incorrect
2) Inside your function, you weren't modifying an object key, but creating a new one instead. Remember that objects keys differs if you use upper or lowercase letters, firstName and firstname are not the same key.
3) Last, when you create an argument in your function, do not declare it with the same name of the global object, since it could create unexpected results. Then, you don´t need to destructure your object, just return the complete object.
let personDetails = { // Using let
firstName: '',
lastName: '',
zipcode: 'xyz',
age: 20,
gender: 'm'
};
const getNames = (obj) => { // obj is the argument
obj.firstName = 'Jack';
obj.lastName = 'Jones';
return obj; // Return complete object
}
personDetails = getNames(personDetails);
console.log(personDetails);
If you want to destructure the object, you can do it too the same way you do it with the array, but I wouldn´t recommend it because it makes the code less clear:
const personDetails = { // Using const
firstName: '',
lastName: '',
zipcode: 'xyz',
age: 20,
gender: 'm'
};
const getNames = (obj) => { // obj is the argument
obj.firstName = 'Jack';
obj.lastName = 'Jones';
return [obj.firstName, obj.lastName]; // Return part of object as an array
}
[personDetails.firstName, personDetails.lastName] = getNames(personDetails);
console.log(personDetails);

How to declare object with different name in Javascript? [duplicate]

This question already has an answer here:
ES6/ES2015 object destructuring and changing target variable
(1 answer)
Closed 2 years ago.
Let's say i declaring an object
let Mahasiswa = {
name: "Steve",
age: 22
}
And then later in my code i copy these code with same name;
let {name, age} = Mahasiswa;
console.log(name, age) // Steve 22
but how do i change it to different variable name?
let {name as Player, age as ID} = Mahasiswa;
console.log(Player, ID) // Steve 22
We use :
let Mahasiswa = {
name: "Steve",
age: 22
}
let {
name: Player,
age: ID
} = Mahasiswa;
console.log({ Player, ID });

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

Object Destructuring ignoring values

I'm trying to destructure and ignore few values, how do I do that?
For example:
const test = { name: 'John', age: 29, gender: 'male'}
function getData(...args) {
const {,,gender} = args[0];
console.log(gender); // should print male.
}
getData(test);
I want to ignore (not declare variables for) name and age parameters (so that my ESLint does not throw an error) at the same time use ES6.
The syntax , does not seem to work either. Any other workarounds for this problem?
You have a single arg (the object), and you should object destructuring to get gender:
const test = { name: 'John', age: 29, gender: 'male'}
function getData(arg) {
const { gender} = arg;
console.log(gender); // should print male.
}
getData(test);

Can I write block of code shorter using ES6/ES7 [duplicate]

This question already has answers here:
One-liner to take some properties from object in ES 6
(12 answers)
Closed 6 years ago.
I have a block of code:
const {address, cityDistrict, city, country} = data;
const obj = {
location: {address, cityDistrict, city, country}
};
But can I write this one shorted? I tried this one, but it's wrong:
const obj = {
location: {address, cityDistrict, city, country} = data
};
Is it possible?
This actually does work (in Chrome at least, in Babel too if you wrap the assignment in parenthesis), but the two pieces of code are not equivalent.
The second piece of code simply assigns data to the location property and creates 4 new variables in scope called address, cityDistrict, etc.
For example:
const data = {
address: "Address",
cityDistrict: "District",
city: "City",
country: "Country"
}
const obj = {
location: ({address, cityDistrict, city, country} = data)
};
console.log(obj);
Looks like it logs the correct data, but what is actually printing is data, not new object. So if we do something like this:
const obj = {
location: ({address, cityDistrict, city, country} = data)
};
data.address = "Test"
console.log(obj); // location.Address = Test
You'd get unexpected data. As a side effect of that, you'd also get 4 new variables in scope:
const obj = {
location: ({address, cityDistrict, city, country} = data)
};
console.log(address, cityDistrict, city, country); // All defined
What you really want to do is to use Object.assign to create a new instance of an object:
const obj = {
location: Object.assign({}, data);
}
This will not work using the es2015 preset, but will work using es2016.
Trying this in https://babeljs.io/repl illustrates this.
Updated
The answer from CodingIntrigue shows why this one does not work.
I also think what you want is currently not achievable with a destructuring one-liner. You'd better stick to your first intent unless you really don't want to have some variables assignments, and in such case you'd likely use an IIFE to filter keys.
As zeroflagl said, you can do it using spread properties if you use ES proposal stage 3.
const data = {
address: 'address',
cityDistrict: 'district',
city: 'city',
country: 'country'
}
const { address, cityDistrict, city, country } = data;
const obj = {
location: {...data}
};
console.log(obj)
/* logs Object {
"location": Object {
"address": "address",
"city": "city",
"cityDistrict": "district",
"country": "country"
}
}
*/
If you want to copy data you can use it:
const obj = {location: Object.assign({}, data)}
Or you also can use next code, but changing obj.location can change data:
const obj = {location: data}

Categories

Resources