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

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 });

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 Constructor with curly {} brackets [duplicate]

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.

How to call object property in another key before execution [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 3 years ago.
I want to call name property in another key. Is it possible? If yes, then how can we achieve this?
let user = {
name: "John",
age: this.name,
};
console.warn(user)
Do you mean like this?
What is it you are trying to achieve?
let userA = {
name: "John",
age: 8
};
let user = {
name: "John",
age: userA.name
};
console.log(user)
I am not in a position to test it at the moment, but I think, in theory, this should work:
let user = {
name: "John"
};
user.age = user.name
console.log(user.age);
// output: John

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' } })

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

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);

Categories

Resources