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

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

Related

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

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 populate an array in javascript if I want to have multiple elements for a single index of an array

How to populate an array in javascript when I want to store multiple elements in a single index?
I want to populate an array in Javascript. What I am trying to do is to store both firstName and lastName of a person in an array index. I am trying to do person[0].firstName = 'Dilshadur'; and then person[0].secondName = 'Rahman'; but It's not working and I think this is not the correct syntax to do so.
person[0].firstName.fill('Md Dilshadur Rahman');
person[0].lastName = 'Rahman';
person[1].firstName = 'Tabassum Monia';
person[1].lastName = 'Disha';
I am getting in the console something like this: "Uncaught TypeError: Cannot read property 'firstName'", I think this because of the wrong syntax and I am not being able to find the correct syntax.
You would have to have an object assigned to each index of the array, and each of those objects would have the firstName and lastName properties.
Ex:
let person = [];
person[0] = {firstName: 'Dilshadur', lastName: 'Rahman'};
person[1] = {firstName: 'Tabassum Monia', lastName: 'Disha'};
You should consider creating a separate class or something where this structure is defined.
class Person {
constructor(first, last) {
this.firstName = first;
this.lastName = last;
}
}
let person = [];
person[0] = new Person('Dilshadur', 'Rahman');
person[1] = new Person('Tabassum Monia', 'Disha');
You need to store an array of objects in that case.
const results = [
{ firstName: 'clark', lastName: 'kent' },
{ firstName: 'bruce', lastName: 'wayne' }
]
You can then use the spread operator to populate the entire index.
const newResults = [
{ firstName: 'peter', lastName: 'parker' },
...results
]
You can also push to your array, however it is good practice to not mutate your data and instead create an updated copy of it.
You can create array of objects
person = [];
person[0] = { firstName: "abc" , lastName: "def" } :
Or you can push values to it by
person.push( { firstName: "abc" , lastName: "def" } )

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

Categories

Resources