I have two objects:
objectA = {
name: 'myname',
surname: 'mysurname',
age: 'myage'
}
objectB = {
birthdate: 'mybirthdate',
school: 'myschool'
}
How can I add objectA's age property to objectB to get the result below:
objectB = {
birthdate: 'mybirthdate',
school: 'myschool',
age: 'myage'
}
There are various ways :
easiest one :
let obj1 = { food: 'pizza', car: 'ford' }
let obj2 = { animal: 'dog' }
Object.assign(obj1, obj2); //es6
console.log(obj1);
Try using either:
objectB.age = objectA.age
or
Object.assign(objectB, { age: objectA.age} );
If you want the object to be a new object (instead of modifying objectB), you can use object rest spread:
objectA = {
name: 'myname',
surname: 'mysurname',
age: 'myage'
}
objectB = {
birthdate: 'mybirthdate',
school: 'myschool'
}
objectC = { ...objectB, age: objectA.age }
console.log(objectC)
Related
Within my Angular application, I need to compare two typescript objects and create a new object that consists of key/value pairs where the value of the key is different in the second object.
Here is my code:
const objBefore = {id: 100088, firstName: "Joe", lastName: "Smith", notes: null};
const objAfter = {id: 100088, firstName: "John", lastName: "Johnson", notes: null};
let newObj = {};
for(let key in objBefore) {
if (objBefore[key] !== objAfter[key]) {
let newEntry = { key: objAfter[key]}
Object.assign(newObj, newEntry)
}
}
console.log(newObj)
The output is:
{ key: 'Johnson' }
I need the output to be:
{ firstName: "John", lastName: "Johnson" }
How do I assign the value of the key (e.g., firstName) instead of the variable (key)?
Just use square brackets on [key]
const objBefore = {id: 100088, firstName: "Joe", lastName: "Smith", notes: null};
const objAfter = {id: 100088, firstName: "John", lastName: "Johnson", notes: null};
let newObj = {};
for(let key in objBefore) {
if (objBefore[key] !== objAfter[key]) {
let newEntry = { [key]: objAfter[key]}
Object.assign(newObj, newEntry)
}
}
I created a form to get some info from User, and I want to move some of their info into a nested object. the reason why is to better organize my data later in front-end.
As a simple example, how to create the following "newInfo" out of "oldInfo" in JavaScript?
oldInfo = {
name: 'John',
Age: '32',
friend1: 'Michael',
friend2: 'Peter',
};
newInfo = {
name: 'John',
Age: '32',
friends: {
friend1: 'Michael',
friend2: 'peter',
},
};
I'm sure this must be a repeated and simple topic, but I couldn't find any as I didn't know what keyword to search for.
You could explicitly assign it
const oldInfo = {
name: "John",
Age: "32",
friend1: "Michael",
friend2: "Peter",
}
const newInfo = {
name: oldInfo.name,
Age: oldInfo.Age,
friends: {
friend1: oldInfo.friend1,
friend2: oldInfo.friend2,
},
}
console.log(newInfo)
You can do this easily with spread operator:
const { name, Age, ...friends } = oldInfo;
newInfo = { name, Age, friends };
It simply extracts all fields except name and age as friends.
Example:
const oldInfo = {
name: 'John',
Age: '32',
friend1: 'Michael',
friend2: 'Peter',
};
const { name, Age, ...friends } = oldInfo;
const newInfo = { name, Age, friends };
console.log(newInfo);
If you have a dynamic number of friend: name key-value pairs and other properties that shouldn't be nested into friends then you can use Object.entries and reduce:
const oldInfo = {
name: 'John',
Age: '32',
friend1: 'Michael',
friend2: 'Peter',
};
const newInfo = Object.entries(oldInfo).reduce((acc, [k, v]) => {
if(k.startsWith('friend')) {
acc.friends ? acc.friends[k] = v : acc.friends = {[k]: v};
} else {
acc[k] = v;
}
return acc;
},{});
console.log(newInfo);
I have two objects.
ObjectA = {name: 'Peter', age: 56, country: 'USA'}
ObjectB = {age: 34}
I want to update ObjectA to become
{name: 'Peter', age: 34, country: 'USA'}
if (ObjectB) {
const newObject = ObjectA[Object.keys(ObjectB)[0]] === ....
}
What would be a better way to update ObjectA?
ES9/Regular Javascript
let object1 = {
foo: 'foo'
}
let object2 = {
bar: 'bar'
}
console.log({ ...object1, ...object2 })
console.log(Object.assign(object1, object2))
Just use Object.assign(ObjectA, ObjectB)
An object is like:
const obj = [{name: 'Alex', age: 20}, {name: 'James', age: 22}];
This obect is immutable from Immutable.js.
Is it possible to add a new key for each object? example:
const obj = [{name: 'Alex', age: 20, city: 'New York'}, {name: 'James', age: 20, city: 'Rome'}];
Not if it’s immutable. But that is ok, you can copy all the properties over to a new structure and add whatever you need to that way:
const newData = obj.map(person => ({
...person,
city: someLogicToDetermineCity(person)
}))
function someLogicToDetermineCity(person) {
// logic based on person
return city
}
const doesn't create immutability - it just means that the reference assigned to it on creation cannot be changed later (which simply means that you cannot assign a new value to it).
See these examples:
const a = {}
a = { name: "peter" } // => TypeError: invalid assignment to const `a'
However it's no problem to assign a property on a:
const a = {}
a.name = "peter"
console.log(a); // => { "name": "peter" }
The same applies for Array objects:
const arr = [{}]
arr.push(1);
arr[0].name="peter"
console.log(arr);
// [
// {
// "name": "peter"
// },
// 1
// ]
For example, I got an object like this:
obj1 = {
name: 'Bob',
age: 20,
career: 'teacher'
}
Now I need to duplicate part of its properties instead all of them.
obj2 = {
name: '',
age: '',
}
I know I can do it like obj2.name = obj1.name, which will be verbose if many properties need to be duplicated. Are there any other quick ways to solve this problem?
I tried
let {name: obj2.name, age: obj2.age} = obj1;
but got error.
Actually you don't need object destructuring, just simple assignment:
obj2 = { name: obj1.name, age: obj1.age }
Now, obj2 holds wanted properties:
console.log(obj2);
// Prints {name: "Bob", age: 20}
If you want to merge old properties of obj2 with new ones, you could do:
obj2 = { ...obj2, name: obj1.name, age: obj1.age }
Drop the let (you're not declaring variables) and surround with parentheses:
({name: obj2.name, age: obj2.age} = obj1);
I guess you can use ES6 Object destructuring syntax
var obj = { name: 'kailash', age: 25, des: 'backenddev'}
({name} = obj);
You could use the target object as template for the properties and assign the values of obj1 with a default value of the target object.
var obj1 = { name: 'Bob', age: 20, career: 'teacher' },
obj2 = { name: '', age: '' };
Object.keys(obj2).forEach(k => obj2[k] = obj1[k] || obj2[k]);
console.log(obj2);
Another solution would be to write a reuable method for this. You can supply an object and the methods you would like to copy.
const duplicatePropertiesFromObject = (obj, propertyNames = [], newObj = {}) => {
Object.keys(obj).forEach((key) => {
if (propertyNames.includes(key)) {
newObj[key] = obj[key];
}
});
return newObj;
}