How to add element key & value to object? - javascript

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

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.

Javascript: How to convert a Map to an Object that has an object as its keys?

let johnB = { name: "John Boy" },
lilyA = { name: "Lily Allen" },
peterD = { name: "Peter Drucker" };
const users = new Map([
[johnB, 'boudler'],
[lilyA, 'rock'],
[peterD, 'stone']
])
const obj = {};
users.forEach((value, key) => obj[key].name = value)
console.log(obj)
The above doesn't work but it shows the basic intent. I want to get name property from the map keys to be the key when the Map is "converted" to an object. Accessing just the key(without .name), javascript stringifies the object so you end up with [object, Object] as the key.
…an Object that has an object as its keys?
That does not exist. An object property cannot have an object as the key, it must be a string or a symbol. What are you attempting to achieve is simply not possible. Keep using the Map - that's what it is meant to be used for.
I think you just have your logic wrong in your foreach loop.. Is this what you were expecting?
{
"John Boy": "boudler",
"Lily Allen": "rock",
"Peter Drucker": "stone"
}
let johnB = { name: "John Boy" },
lilyA = { name: "Lily Allen" },
peterD = { name: "Peter Drucker" };
const users = new Map([
[johnB, 'boudler'],
[lilyA, 'rock'],
[peterD, 'stone']
])
const obj = {};
users.forEach((value, key) => obj[key.name] = value)
console.log(obj)

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

Modify JS Object in Pure Way

I have a function that transforms a JS object. It derives a new property from an existing one, then deletes the original property. Essentially something like this:
/** Derives "capName" property from "name" property, then deletes "name" */
function transform(person) {
person["capName"] = person["name"].toUpperCase();
delete person["name"];
return person;
}
var myPerson = {
name: "Joe",
age: 20
};
var newPerson = transform(myPerson);
console.log(myPerson, newPerson);
The function returns the desired newPerson object, but also modifies the original myPerson object. I would rather do this in a pure way, that doesn't modify the original myPerson object.
Note: I really need to be ES5 compatible, but I'd like to see the ES6 solution as well.
Quite easy with destructuring:
const transform = ({ name, ...rest }) => ({ capName: name.toUpperCase(), ...rest });
I really need to be ES5 compatible
Use BabelJS, it makes your life so much eaiser.
just use Object.assign which will create a new object with new reference
function transform(person) {
var obj = Object.assign({}, person);
obj["capName"] = obj["name"].toUpperCase();
delete obj["name"];
return obj;
}
var myPerson = {
name: "Joe",
age: 20
};
var newPerson = transform(myPerson);
console.log('newPerson:', newPerson);
console.log('myPerson:', myPerson);
For ES5 compatibility, you can use JSON.parse(JSON.stringify(person)). Be aware that methods attached to person are lost on the way because they cannot properly be JSON.stringifyed.
/** Derives "capName" property from "name" property, then deletes "name" */
function transform(person) {
var obj = JSON.parse(JSON.stringify(person));
obj["capName"] = obj["name"].toUpperCase();
delete obj["name"];
return obj;
}
var myPerson = {
name: "Joe",
age: 20
};
var newPerson = transform(myPerson);
console.log(myPerson, newPerson);
If you want to retain methods, just iterate over the object keys:
/** Derives "capName" property from "name" property, then deletes "name" */
function transform(person) {
var obj = {};
for (var key in person) {
obj[key] = person[key];
}
obj["capName"] = obj["name"].toUpperCase();
delete obj["name"];
return obj;
}
var myPerson = {
name: "Joe",
age: 20
};
var newPerson = transform(myPerson);
console.log(myPerson, newPerson);
Be aware that none of the methods presented does a deep clone. For that, I'd recommend you use something like lodash's _.clone(obj, { deep: true });
You could generate a new object without the unwanted and a new property.
function transform(person) {
return Object
.keys(person)
.reduce(function (r, k) {
if (k === 'name') {
r.capName = person.name.toUpperCase();
} else {
r[k] = person[k];
}
return r;
}, {});
}
var myPerson = { name: "Joe", age: 20 },
newPerson = transform(myPerson);
console.log(myPerson);
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