I assign a object:
const info = { name: 'Peter', location: { province: 1, city: 2 } };
let { name } = info;
console.log(name); // 'Peter'
// then how to get location.province
let { 'location.province': province } = info;
console.log(province); // 'undefined'
how to I get sub-object location.province by deconstruct???
By doing "nested" destructuring:
let {name, location: {province}} = info;
For such questions, always look at MDN first because it usually has many examples.
Related
I have a data object below.
{
name: "Catherine Myer",
age: 23,
birthday: "august"
}
If in need to pass the data as a prop to a component, BUT would also like to change just the age to: 24. How do i do so?
<NextPage data={author.age = 24}/>
I need the final object to be:
{
name: "Catherine Myer",
age: 24,
birthday: "august"
}
You can do it with spread syntax:
<NextPage data={{...author, age: 24}}/>
Either pass individual prop values by spreading author (see Spread Attributes) and override age with a separate prop, eg
const NextPage = ({ name, age, birthday }) => {
// ...
};
<NextPage {...author} age="24" />
or extend the existing object and provide a new age property
const NextPage = ({ data: { name, age, birthday } }) => {
// ...
};
<NextPage data={{...author, age: 24}} />
You can just use the JS spread syntax to update whichever properties you need.
const author = {
name: "Catherine Myer",
age: 23,
birthday: "august"
};
const data = {
age: 24
};
const updatedAuthor = { ...author, ...data };
Edit: I have no idea what I was thinking to make it this complicated...
If you don't know which property will be overwritten, a simple for in loop can make the update. As a bonus, this scales up if you want to modify the value of more than one property at once.
Alternatively, if you really want to (or if you make the change Mike Kamermans recommended), you can use the JS spread syntax to achieve the same.
const author = {
name: "Catherine Myer",
age: 23,
birthday: "august"
};
const data = {
age: 24
};
// OPTION 1: for in loop
let updatedAuthor = { ...author }; // optionally create a copy to avoid mutating the original object
for(let prop in data) {
updatedAuthor[prop] = data[prop];
}
// OPTION 2: spread syntax
const propToUpdate = Object.keys(update)?.[0];
const updatedAuthor = {
...author,
[propToUpdate]: update[propToUpdate]
}
so I've encountered a problem with assigning object values to class values. Basically, let's say that I have a class Account and an object with the same properties as the class
class Account {
id: Number;
name: String;
}
const accountObject = {
id: 4216,
name: "Test name"
}
const account = new Account();
//set values from accountObject to account as a class
account.id = accountObject.id;
//...
So is there a way to assign values from an object to a class without doing it manually? I have a lot of properties that I need to be assigned and doing it by hand would solve the issue but if there's a prettier way to do so, I'd really appreciate any help
A simple loop should do the trick:
class Foo {
name = "foo"
age = 1
}
const foo = new Foo()
const bar = {
name: "bar",
age: 100
}
for (let key in bar) {
foo[key] = bar[key]
}
console.log(foo) // prints Foo { name: 'bar', age: 100 }
console.log('----------------------------------');
Object.entries(bar).forEach(
([key, value]) => (foo[key] = value)
)
console.log(foo) // prints Foo { name: 'bar', age: 100 }
class Account {
constructor({
id,
name
}) {
this.id = id;
this.name = name;
}
}
const account = new Account({
id: 4216,
name: "Test name"
});
console.log(account);
I have object in this structure:
obj = {
user: { name: 'jeterson' },
title: 'I am a test'
}
I have one key with value: user.name.
I have trying get value like this: obj[key], meaning obj['user.name']. It not works, only works for obj.title.
My object have many values that are also objects, and i want get value like this:
myobject[mykey]
It is possible get value from property object like above ?
You can access it with:
obj['user']['name']
Or alternatively:
obj.user.name
If you want to get from a key like "user.name" to the value, you woulr have to do some logic yourself. You could hack something together like this:
let obj = {
user: {
name: 'jeterson'
},
title: 'I am a test'
}
let key = 'user.name';
let keys = key.split('.');
let res = obj;
while (keys.length > 0 && res) {
let k = keys.shift();
res = res[k];
}
console.log(res) // "jeterson"
When the keys do not match, res holds undefined.
You've got multiple solutions to access an element of an object with its keys:
var obj = {
user: { name: 'jeterson' },
title: 'I am a test'
}
console.log(obj['user']['name']);
console.log(obj['user'].name);
console.log(obj.user['name']);
console.log(obj.user.name);
But you can't do it easily with a variable key = 'user.name'.
If you need to use a variable containing the nested-keys, you could create a function.
Updated answer: An amazingly short way to achieve it is to use .reduce():
// My function
function obj_tree_key(obj, path) {
return path.split('.').reduce((accu, val) => accu[val] || 'Not found', obj);
}
var obj1 = {
user: {
name: 'jeterson'
},
title: 'I am a test'
}
console.log(obj_tree_key(obj1, 'user.name')); // Outputs "jeterson"
// Here is an example with error:
var obj2 = {
user: {
nameeeee: 'jeterson'
},
title: 'I am a test'
}
console.log(obj_tree_key(obj2, 'user.name'));
Old answer: Use a for to loop through the keys and reduce the oject:
// My function
function obj_tree_key(obj, tree_key) {
var result = obj;
var keys = tree_key.split('.');
for (var i = 0; i < keys.length; i++) {
result = result[keys[i]] || 'Not found'; // Error handling
}
return result;
}
var obj1 = {
user: {
name: 'jeterson'
},
title: 'I am a test'
}
console.log(obj_tree_key(obj1, 'user.name')); // Outputs "jeterson"
// Here is an example with error:
var obj2 = {
user: {
nameeeee: 'jeterson'
},
title: 'I am a test'
}
console.log(obj_tree_key(obj2, 'user.name'));
Hope it helps.
first get the user, then the name:
obj['user']['name']
or
obj.user.name
You can also use
obj.user.name
You could access it using
console.log(obj.user.name);
You can do it in 2 way:
obj['user']['name']
or
obj.user.name
I am trying to add key value from array to person object, i mocked below code similar approach it is coming undefined object when we assign key/value pair to object. What would be right approach to achieve this task ?
main.js
const person = {
Name: "John klmeni"
age: 29
}
const address = [{address: '111 main st"}]
for (let obj in person) {
address.forEach(element ,==> {
obj[key] = element.key
}
}
I think you want to do the following?
const person = {
Name: "John klmeni",
age: 29
}
const address = [{address: '111 main st'}];
const newPerson = address.reduce(
(result,item)=>
Object.assign({},result,item),
person
);
console.log(newPerson);
I have a scenario, where I receive an obj from a promise, and need to add some keys of this object to another object. For example:
// Received from promise
object_1 = {
name: 'SH'
};
// Want to add object_1.name to object_2
object_2 = {
id: 1234
};
Normally I could do like following, but I want to do it with object destructuring
object_2.name = object_1.name;
to have:
object_2 = {
id: 1234,
name: 'SH'
};
You could use a destructuring assignment to a target object/property with a object property assignment pattern [YDKJS: ES6 & Beyond].
var object_1 = { name: 'SH' },
object_2 = { id: 1234 };
({ name: object_2.name } = object_1);
console.log(object_2);
You can achieve the expected output by using object destructing like this:
// Received from promise
object_1 = {
name: 'SH'
};
// Want to add object_1.name to object_2
object_2 = {
id: 1234
};
object_2 = {
...object_2,
...object_1
}