dynamically merging(override) 2 javascript objects [duplicate] - javascript

This question already has answers here:
How to deep merge instead of shallow merge?
(47 answers)
Merge two objects and overwrite the values if conflict
(4 answers)
Closed 2 years ago.
I have 2 objects .
userprofile = {
id: 1,
email: hello #gmail.com,
user: {
id: 1,
username: test,
}
}
userprofile2 = {
email: bye #gmail.com,
user: {
username: testtest,
}
}
What i wish to do is to merge userprofile and userprofile2 , or in a sense using userprofile2 to override userprofile.
Here is what i wish to obtain:
updatedprofile = {
id: 1,
email: bye #gmail.com,
user: {
id: 1,
username: testtest,
}
}
The application for this problem is because i have an update form which uses redux saga . The change in data is userprofile2 while the previous data is userprofile.
Is there a simple efficient way to do this?

You could use the spread operator. As the ... operator only performs a shallow merge, you will have to spread the nested user property as well.
const userprofile = {
id: 1,
email: "hello #gmail.com",
user: {
id: 1,
username: "test",
}
}
const userprofile2 = {
email: "bye #gmail.com",
user: {
username: "testtest",
}
}
const updatedProfile = {
...userprofile,
...userprofile2,
user: {
...userprofile.user,
...userprofile2.user,
}
};
console.log(updatedProfile)

Related

How to add new object value to an array [duplicate]

This question already has answers here:
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Array.includes() to find object in array [duplicate]
(8 answers)
Javascript: Using `.includes` to find if an array of objects contains a specific object
(7 answers)
Closed 7 months ago.
Trying to add new object value in an array but not working. How to add it? If anyone knows please help to find the solution.
getting this error:
Property 'includes' does not exist on type '{ name: string; id:
string; }[]'. Do you need to change your target library? Try changing
the 'lib' compiler option to 'es2016' or later.
app.component.ts:
public a = { name: 'test1', id: '12345' };
public b = { name: 'test2', id: '12345' };
addVala() {
if (this.arr.includes(this.a)) {
console.log('This obj already there');
} else {
this.arr.push(this.a);
}
console.log(this.arr);
}
Demo : https://stackblitz.com/edit/angular-ivy-jj7sna?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.ts
You can simplify your "add" logic by passing-in the object that you want to add and checking if another object (already in the list) shares the same ID.
const arr = [
{ name: 'test1', id: 'A' },
{ name: 'test3', id: 'C' },
];
const a = { name: 'test1', id: 'A' };
const b = { name: 'test2', id: 'B' };
const add = (obj) => {
if (!arr.find(({ id }) => id === obj.id)) {
arr.push(obj);
console.log(`Added ${obj.id}`);
} else {
console.log(`Object ${obj.id} already exists!`);
}
}
function addA() { add(a); }
function addB() { add(b); }
<button onclick="addA()">Add A</button>
<button onclick="addB()">Add B</button>

Omit object's key-value if value == null [duplicate]

This question already has answers here:
In JavaScript, how to conditionally add a member to an object?
(29 answers)
Closed 2 years ago.
Having typescript code presented below, which creates new record in the Firestore database, is it possible to omit (by writing one line of inline code) one of the key-value pair if the value equals null?
firestore.doc(`users/${user.uid}`).set({
email: user.email,
name: user.displayName,
phone: user.phoneNumber, // (user.phoneNumber ? phone: user.phoneNumber), ... ?
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
});
You can use the object destruction with ternary expression to do it:
firestore.doc(`users/${user.uid}`).set({
email: user.email,
name: user.displayName,
...(user.phoneNumber ? { phone: user.phoneNumber } : undefined),
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
});
It's not very elegant, but it get its job done in one line:
const phone = null;
const obj = {
name: 'Alice',
age: 24,
...(phone ? { phone } : undefined),
};
console.log(obj);
Edit
According to this answer that ford04 mentioned, it also can be shortened like this:
...(user.phoneNumber && { phone: user.phoneNumber }),
Edit, again
But it's better to check its type properly that it might cause 0 and "" are not stored correctly
...(![undefined, null].includes(user.phoneNumber) && { phone: user.phoneNumber })

How to remove an element from an array in a nested object? (lodash) [duplicate]

This question already has answers here:
How can I remove an element from a list, with lodash?
(10 answers)
Closed 3 years ago.
I had an object like
data: {
registrationNumber: 'MH1234',
type: 'xyz',
driver: {
user: {
firstName: 'xyz',
lastName: 'abc',
email: 'xyz',
phone: 1234,
city: 'random',
dateOfBirth: new Date(),
groups: [1]
}
},
owner: {
user: {
firstName: 'xyz',
lastName: 'abc',
email: 'xyz',
phone: '1234',
city: 'random',
groups: [1, 2]
},
kyc: [
{
method: 'xyz',
id: 'abcd'
},
{
method: 'xyz',
id: 'abcd'
}
]
}
}
how can i remove the element at path data.owner.kyc.0 ?
I have tried using _.unset() but it is not ideal since the array still shows 2 elements after deletion
You don't need lodash to accomplish this.
With .shift() to remove first element from array.
let newData = {...data}
newData.owner.kyc.shift()
With .splice() to remove elements from a certain point.
let newData = {...data}
newData.owner.kyc.splice(0, 1)
With .filter() to remove items that don't match a specified condition
let newData = {...data}
newData.owner.kyc = newData.owner.kyc.filter((item, index) => {
return index !== 0
})
Since you're using React, you would want to have this data in component-state so that when you actually remove something from the array, the App updates to reflect the new results.
See sandbox: https://codesandbox.io/s/mystifying-fog-2yhwd
class App extends React.Component {
state = {
data: data
};
removeFirstItem = () => {
const { data } = this.state;
let newData = { ...data };
newData.owner.kyc.shift();
this.setState({
data: newData
});
};
render() {
const { data } = this.state;
return (
<div>
<h4>Car Info:</h4>
<div>
KYC:
{data.owner.kyc.map((item, index) => {
return (
<div>
<span>{index + 1}) </span>
{item.id}
</div>
);
})}
</div>
<button onClick={this.removeFirstItem}>Remove first item</button>
</div>
);
}
}
You can use _.remove or _.filter.
Please refer this example
You can use a Array prototype method itself,
if you want to remove from the front
Array.prototype.shift.apply(data.owner.kyc,null)

using nested destructuring with aliasing for javascript Object [duplicate]

This question already has answers here:
Destructuring deep properties
(4 answers)
Closed 4 years ago.
I have this object
const storeObj = {
name: {
firstName: 'abc'
}
}
I can do alias by assigning name to username
const { name: username } = storeObj
I can do nested destructuring like so
const { name: { firstName } } = storeObj
Can I use them both together? I want to achieve one line when aliasing aka renanming and nested destructuring.
Yes, just put those two together - when you want to assign to a different variable name than the property name, put the new variable name after a colon. This works regardless of the level of the nested object.
const storeObj = {
name: {
firstName: 'abc'
}
}
const { name: { firstName: username } } = storeObj;
console.log(username);

Firebase Functions - Loop through event value [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
A firebase event which listents for changes.
exports.sendTestEmail = functions.database.ref('/email/{pushID}')
.onWrite(event => {
// Only edit data when it is first created.
if (event.data.previous.exists()) {
return;
}
// Exit when the data is deleted.
if (!event.data.exists()) {
return;
}
return sendTestEmail(event);
});
function sendTestEmail(email, event) {
const users = event.data.val();
console.log(users);
});
}
this is the result for console.log(users):
{ '-Km8VHEPHExBtpIN_7q0':
{ admin: 'false',
birthday: '76',
description: 'desc',
email: 'user#gmail.com',
first_name: 'fname',
last_name: 'lname',
level: 5,
occupation: 'dev',
occupationLevel: 'dev5',
phone: '+8766',
verified: false },
'-KmSjAaxdCUvrPEQ8InI':
{ admin: 'false',
birthday: '1990',
description: 'desc',
email: 'email2#gmail.com',
first_name: 'fname',
last_name: 'lanam3',
level: 4,
occupation: 'dev',
occupationLevel: 'dev4',
phone: '+23434',
verified: false } }
I can't seem to loop and get the emails which are needed for sending emails to users who own the email addresses.
Maybe consider something like this.
function sendTestEmail(event) {
emails = []; // create empty email array
const users = event.data.val(); // get users, as you currently were.
for (var key in users) { // loop through users to retrieve key.
var email = users[key].email; // get email using key
emails.push(email); // push to emails array
}
return emails;
}

Categories