how to destruct part of properties from an object - javascript

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

Related

Condition Spread based on Object props

I'm looking for way to remove empty or null props, on my example obj2, I want to avoid copying the birthPlace property or any other prop that comes empty.
const obj1 = { firstName: 'Foo', age: 22 };
const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };
const newObj = { ...obj1, ...obj2 };
Desired result:
{firstName: 'Foo', age: 22, lastName: 'Bar', gender: 'M'}
Is it possible using Conditional Objects props using Spread Operators in javascript?
const updateUserObj = {
...(obj1 !== check here<hasPropEmpty> && obj2)
}
There's no shorthand for it, but you can easily write a function that filters out those properties.
function nonEmptyProps(obj) {
return Object.fromEntries(Object.entries(obj).filter(([k, v]) => v !== null && v !== ''));
}
const obj1 = { firstName: 'Foo', age: 22 };
const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };
const newObj = {...nonEmptyProps(obj1), ...nonEmptyProps(obj2)};
console.log(newObj);
Using Object#entries you get the key-value pairs of an object, then, using Array#filter you iterate over these pairs to filter out the ones with empty values. Then, using Object#fromEntries you construct back the resulting pairs to an object.
const filterProps = (obj = {}) =>
Object.fromEntries(
Object.entries(obj).filter(([key, value]) =>
value !== null && value !== undefined && value !== ''
)
);
const obj1 = { firstName: 'Foo', age: 22 };
const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };
const newObj = { ...filterProps(obj1), ...filterProps(obj2) };
console.log(newObj);

Js ES6, Merge 2 objects and store in array instead replacing existent key

i have the following
let user = { name: 'John', lastName: 'Doe', phone: '000111222' };
let otherInfo = { phone: '123456', age: '30' };
After merging both
let result = { ...user, ...otherInfo };
I got
{ name: 'John', lastName: 'Doe', phone: '123456', age: '30' };
Base on this, the phone is duplicated entry, i want to keep the old phone and keep both in array, based on ES6 spread, note: (i can do iterating object, but is better to write less code)
{ name: 'John', lastName: 'Doe', phone: ['000111222', '123456'], age: '30' };
Some ideas?, thank you in advance.
Merge the objects together, and get all unique keys with Object.keys(). Reduce the keys, and check if the key exists in the objects. If it exists in both of them, combine the values to an array. If it doesn't take the value from one of the objects:
const fn = (o1, o2) => Object.keys({ ...o1, ...o2 }) // get combined keys
.reduce((acc, key) => {
// if key exists it both object combine the values in an array
if (key in o1 && key in o2) acc[key] = [o1[key], o2[key]];
// take the value from o1 or o2
else acc[key] = key in o1 ? o1[key] : o2[key];
return acc;
}, {});
const user = { name: 'John', lastName: 'Doe', phone: '000111222' };
const otherInfo = { phone: '123456', age: '30' };
const result = fn(user, otherInfo);
console.log(result);
You can do this:
let result = { ...user, ...otherInfo, phone: user.phone && otherInfo.phone ? [user.phone, otherInfo.phone]: user.phone || otherInfo.phone };
For a generic solution, where you would maybe need to merge more than two objects, you could apply Object.entries on each of the objects and create a flat array of the resulting pairs. Then use these pairs to extend the result object. When a pair references a key that is already in the result object, use [].concat to silently merge that value with the new value into an array. This also works if the stored value was already an array with two or more previously found values.
Here is a snippet:
const user = { name: 'John', lastName: 'Doe', phone: '000111222' };
const otherInfo = { phone: '123456', age: '30' };
const moreInfo = { phone: '9876543', hometown: 'Paris' };
let res = {};
for (let [k, v] of [user, otherInfo, moreInfo].flatMap(Object.entries)) {
res[k] = k in res ? [].concat(res[k], v) : v;
}
console.log(res);
THIS
1 line of code
let result = Object.assign({}, info, otherInfo, {phone: [info.phone, otherInfo.phone]})
the Object.Assign is more faster

How overwrite and combine two objects in js?

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)

How to map an Object's property to another object?

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)

Can we add properties to immutable object in JavaScript?

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

Categories

Resources