decompose object to this attributes - javascript

I am trying to decompose an object into attributes as follows;
let example = {name: 'Fred', age:20}
const {name, age} = example;
But, I would like it to do to the this.name, and this.age of the class it is in. Something like;
class Test = {
name: ''
age: null
constructor(example) {
{this.name, this.age} = example;
}
}
Is this possible?

It is possible to assign value to objects using destructuring. It is definitely NOT recommended. You can see why:
class Test {
name = ''
age = null
constructor(example) {
({ name: this.name, age: this.age } = example) // <- dont't forget the parenthesis
}
}
console.log(
new Test({ name: 'name', age: 10 })
)
If the properties of example and the class are same, you can just use Object.assign
class Test {
name = ''
age = null
constructor(example) {
Object.assign(this, example)
}
}
console.log(
new Test({ name: 'name', age: 10 })
)

Related

How to pass an object and only change one value?

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]
}

Set adds same object to the list - Javascript

Is there a way to check if the objects have the same that before inserting them into the Set?
let mySet = new Set();
let person = {
name: 'John',
age: 21
};
let person2 = {
name: 'John',
age: 21
};
mySet.add(person);
mySet.add(person2);
console.log(JSON.stringify([...mySet]));
Is there a way to check if the objects have the same that before inserting them into the Set?
Only by doing it yourself by iterating the set, since they're different (though equivalent) objects; as is always the case, two different objects aren't "equal" to each other for any of JavaScript's built-in operations. And sets don't offer methods like some or find like arrays do.
For instance, you might use a utility function:
function setFind(set, predicate) {
for (const element of set) {
if (predicate(element)) {
return element;
}
}
}
Then:
if (!setFind(mySet, ({ name, age }) => name === person2.name && age == person2.age)) {
mySet.add(person2);
}
let mySet = new Set();
let person = {
name: 'John',
age: 21
};
let person2 = {
name: 'John',
age: 21
};
mySet.add(person);
if (!setFind(mySet, ({ name, age }) => name === person2.name && age == person2.age)) {
mySet.add(person2);
}
console.log(JSON.stringify([...mySet]));
function setFind(set, predicate) {
for (const element of set) {
if (predicate(element)) {
return element;
}
}
}
Or just use a loop, or use some or find after converting to an array:
let contains = [...mySet].some(({ name, age }) => name === person2.name && age == person2.age);
if (!contains) {
mySet.add(person2);
}
let mySet = new Set();
let person = {
name: 'John',
age: 21
};
let person2 = {
name: 'John',
age: 21
};
mySet.add(person);
let contains = [...mySet].some(({ name, age }) => name === person2.name && age == person2.age);
if (!contains) {
mySet.add(person2);
}
console.log(JSON.stringify([...mySet]));
Or similar.

Shorthand for picking object properties - combine ES6 `Object Deconstruction` with `Object Property Value` shorthand

Following code outputs {name: "Bob", surname: "Smith"} and it works fine. I want to know can I make it shorter.
((person = { name: 'Bob', surname: 'Smith', age: 22, }) => {
const {
name, // (a) create variable from deconstructing
surname,
} = person;
return {
name, // (b) reuse variable as new object parameter name (and value)
surname
}
})();
Can I somehow merge object deconstruction to variables (a) with returning a new object with Object Property Value shorthand (b)?
I use here shorthand but then its purpose is defeated by the need to manually re-use parameters. I want to mention the name or surname word in my function once not twice...
Destructure person in the function's declaration:
const result = (({ name, surname } = { name: 'Bob', surname: 'Smith', age: 22, }) => ({
name, // (b) reuse variable as new object parameter name (and value)
surname
}))();
console.log(result);
You can not mention it at all
((person = { name: 'Bob', surname: 'Smith', age: 22, }) => {
const {age,...ans} = person;
return ans
})()

Assign object values to class values

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

js destruct a sub-object inner object

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.

Categories