Assign object values to class values - javascript

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

Related

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.

Get arguments of constructor in JS class

How can i get an array of the arguments of a constructor class in JS? It's possible? Thanks in advance.
class Product {
constructor(id, name, price, category, stock){
this.id = id;
this.name = name;
this.price = price;
this.category = category;
this.stock = stock;
}
};
console.log(Product.constructor.params);
//expected output = ['id', 'name', 'price', 'category', 'stock'];
Inspired form #Porter answer and #evolutionxbox, I think that a reliable way would be using .match() like this:
class Product {
constructor(id, name, price, category, stock, unusedArgument) {
this.id = id;
this.name = name;
this.price = price;
this.category = category;
this.stock = stock;
}
}
class Noarguments {
constructor() {
}
}
// A function
function getClassContructorParams(obj){
let match = obj.toString().match(/constructor\((.+)\)/)
if(match && match[1]){
return match[1].split(",");
}
// If no match
return []
}
console.log(getClassContructorParams(Product))
/// Testing a class with no constructor arguments will return an empty array
console.log(getClassContructorParams(Noarguments))
My previous answer was returning the object properties, which may be different from the arguments used in the constructor...
Now using .match() will ensure what is returned really are the constructor arguments.
let s = Product.toString();
let params = s.substring(s.indexOf('(')+1, s.indexOf(')')).split(',')
My point in the comments was it seems you're coming at this problem from the wrong direction. Maybe take this approach. Have an array of labels, and array of data, and pass those into the class. You'll still have the array of labels to access (and validate) in your other code, and everything will still work.
const labels = [ 'id', 'name', 'price', 'category', 'stock' ];
const data = [ 1, 'Bob', 100, 2, 1];
class Product {
constructor(labels, data) {
data.forEach((el, i) => this[labels[i]] = el);
}
};
console.log(new Product(labels, data));
console.log(labels);
Or, if your products are identical in terms of properties you could just use an array of them, and use Object.keys to get the labels of the first object.
const data = [{ id: 1, name: 'Bob', price: 100, category: 2, stock: 1 }];
const labels = Object.keys(data[0]);
class Product {
constructor(data) {
for (let key in data) {
this[key] = data[key];
}
}
};
console.log(new Product(data[0]));
console.log(labels);

decompose object to this attributes

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

How to add element key & value to object?

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

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