using nested destructuring with aliasing for javascript Object [duplicate] - javascript

This question already has answers here:
Destructuring deep properties
(4 answers)
Closed 4 years ago.
I have this object
const storeObj = {
name: {
firstName: 'abc'
}
}
I can do alias by assigning name to username
const { name: username } = storeObj
I can do nested destructuring like so
const { name: { firstName } } = storeObj
Can I use them both together? I want to achieve one line when aliasing aka renanming and nested destructuring.

Yes, just put those two together - when you want to assign to a different variable name than the property name, put the new variable name after a colon. This works regardless of the level of the nested object.
const storeObj = {
name: {
firstName: 'abc'
}
}
const { name: { firstName: username } } = storeObj;
console.log(username);

Related

How to add new object value to an array [duplicate]

This question already has answers here:
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Array.includes() to find object in array [duplicate]
(8 answers)
Javascript: Using `.includes` to find if an array of objects contains a specific object
(7 answers)
Closed 7 months ago.
Trying to add new object value in an array but not working. How to add it? If anyone knows please help to find the solution.
getting this error:
Property 'includes' does not exist on type '{ name: string; id:
string; }[]'. Do you need to change your target library? Try changing
the 'lib' compiler option to 'es2016' or later.
app.component.ts:
public a = { name: 'test1', id: '12345' };
public b = { name: 'test2', id: '12345' };
addVala() {
if (this.arr.includes(this.a)) {
console.log('This obj already there');
} else {
this.arr.push(this.a);
}
console.log(this.arr);
}
Demo : https://stackblitz.com/edit/angular-ivy-jj7sna?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.ts
You can simplify your "add" logic by passing-in the object that you want to add and checking if another object (already in the list) shares the same ID.
const arr = [
{ name: 'test1', id: 'A' },
{ name: 'test3', id: 'C' },
];
const a = { name: 'test1', id: 'A' };
const b = { name: 'test2', id: 'B' };
const add = (obj) => {
if (!arr.find(({ id }) => id === obj.id)) {
arr.push(obj);
console.log(`Added ${obj.id}`);
} else {
console.log(`Object ${obj.id} already exists!`);
}
}
function addA() { add(a); }
function addB() { add(b); }
<button onclick="addA()">Add A</button>
<button onclick="addB()">Add B</button>

loop through a dynamic key of an object in a array [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 11 months ago.
I have 2 arrays. The one contains the name of all the keys of the 2nd array like the following.
const additionalFields = ['phoneNumbers', 'ageOrDobs', 'genders', 'usernames', 'employments', 'educations', 'websites', 'affiliatedOrganizations'];
const fields= [{
affiliatedOrganizations: []
ageOrDobs: []
educations: []
emails: [{…}]
employments: []
genders: []
locations: [{…}]
names: [{…}]
phoneNumbers: []
usernames: []
websites: []
}]
Now, I want to loop through the additionalFields based on the value I receive I want to check if the key of fields have length greater than 0. For example.. fields.phonenNumbers.length > 0 but the key phoneNumbers will be coming from loop
additionalFields.map((opts) => {
if(fields.opts.length > 0){ //this one doesn't work...
//do something
}
}
I am using typescript and fields have a interface related to the values in it as shown above. Please help me with this... thank you!!
Just use the Bracket notation:
additionalFields.map((opts) => {
if(fields[opts].length > 0){ //this one doesn't work...
//do something
}
}
Example:
const person = {
firstname: 'John',
lastname: 'Doe'
}
const key = "firstname"
console.log(person[key]) // John

Object.assign can`t find declared variable [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 2 years ago.
I feel like my problem is really easy to solve, but I cannot see it. I have simple thing to do, get myObject from another function and store this in my storage object. For this task I created storageHandler function. Everything works fine, but Object.assign is not reaching my 'ID' that I declared in this function earlier. This is weird because I don't know how to tell my function that 'ID' is variable, not a string. I just expect it to be {1212313: {...}} but instead it gives me {ID: {...}}.
Someone have any idea how to fix it?
let storage = {}
const myObject = {
ID: '1223424525221',
name: 'Thomas',
mail: 'example#example.com'
}
storageHandler = data => {
const {ID} = data;
Object.assign(storage, {ID: data})
console.log(storage)
}
storageHandler(myObject)
That's because in javascript this
a = { b: 1 };
is the same as
a = { "b": 1 };
You should change the Object.assign() for something like this
storage[ID] = data;
You should use the value of ID as key of object using [].
Object.assign(storage, {[ID]: data})
You are using string as a property name. Use computed property name like [ID] instead of ID. Computed property allows you to have an expression be computed as a property name on an object.
let storage = {};
const myObject = {
ID: '1223424525221',
name: 'Thomas',
mail: 'example#example.com',
};
storageHandler = (data) => {
const { ID } = data;
Object.assign(storage, { [ID]: data });
console.log(storage);
};
storageHandler(myObject);

referencing outer layer of nested object in javascript in object literal [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 3 years ago.
I'm looking to do something like the task here Self-references in object literals / initializers , except that it would be for the value of an aunt/uncle key, or the sibling key of the parent object. For example:
const obj = {
parent: {
child: {
aunt: /* aunt object */
}
},
aunt: {
foo: {
bar: 1
}
}
}
There's a very similar ask here Reference nested 'sibling'-property in object literal but unfortunately, not quite what I'm looking for. Ideally, the solution would be extensible and probably would need to be to handle cases where I'd want to access a great-grandcousin object related to a key if need be. Thanks!
It's not possible in a single object literal. You'd have to define the object first, then assign to the aunt key .
const obj = {
parent: {
child: {
}
},
aunt: {
foo: {
bar: 1
}
}
};
obj.parent.child.aunt = obj.aunt;
console.log(obj.parent.child.aunt === obj.aunt)
Or, you can define aunt beforehand:
const aunt = {
foo: {
bar: 1
}
};
const obj = {
parent: {
child: {
aunt
}
},
aunt
};
console.log(obj.parent.child.aunt === obj.aunt)

How to pass index of an array without hardcoding to update method of 'react-addons-update'? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Creating object with dynamic keys [duplicate]
(2 answers)
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 4 years ago.
nameChangedHandler = (id, event) => {
let index = id;
const updatedName = event.target.value;
this.setState({
persons: update(this.state.persons, { index: { name: { $set: updatedName } } }),
});
};
If I hardcode the index to any number the above code is working i.e ( update(this.state.persons, { 0: { name: { $set: updatedName } } }) )
Kindly Suggest a Solution.
replace { index: ... } with { [index]: ... }
You can use a computed property to use the value of the index variable:
this.setState({
persons: update(this.state.persons, { [index]: { name: { $set: updatedName } } }),
});

Categories