How to merge/add variable in angular - angularjs

Below is my user object. Once i submit form i am getting values for it along with priPhone , mobilePhone.
this.user = {
isActive: 1,
contactDetails: {
name: { }
},
};
}
mobilePhone:any={phoneNumber: '',type:'Mobile'};
primaryPhone:any={phoneNumber: '',type:'Primary'};
I have to set mobilePhone, primaryPhone details to User Object.
So that i want final object like this.
this.user = {
isActive: 1,
contactDetails: {
name: { }
},
phoneNumbers: [{
phoneNumber: '',
type: 'Primary'
}, {
phoneNumber: '',
type: 'Mobile'
}]
};
How to do it ?

This should work in javascript.
this.user.phoneNumbers = [];
this.user.phoneNumbers.push(mobilePhone);
this.user.phoneNumbers.push(primaryPhone);
or simply
this.user.phoneNumbers = [mobilePhone, primaryPhone];

Related

How to set state in nested array of objects in ReactJs?

I have this object as a state in reactjs. I want to add another object inside the "childoptions: []" array which is nested inside the options array on button click.
How can I achieve this, pls help...
const [select1, setSelect1] = useState({
id: uuid(),
type: 'select',
properties: {
label: 'Select1',
options: [
// {
// id: uuid(),
// optionName: 'red 🔴',
// value: '',
// childOptions: [],
// },
// {
// id: uuid(),
// optionName: 'green 🟢',
// value: '',
// childOptions: [],
// },
// {
// id: uuid(),
// optionName: 'blue 🔵',
// value: '',
// childOptions: [],
// },
],
},
parentId: null,
});
This is achievable by copy the prevState in the new state with the new object inserted inside the options array.
A more detailed explanation could be found at https://stackoverflow.com/a/26254086/9095807
setSelect1((prevState) => {
return {
...prevState,
properties: {
label: 'Select1',
options: prevState.properties.options.map(obj => obj.id === id ? { ...obj, childOptions: [...obj.childOptions, newChildOptions] } : obj),
}
}
})

How to convert Array of Object into Object in React

GetQuery
sample data from getquery graphql generated api
{
id: '',
name: '',
regions: [
{
id: '',
name: '',
districts: [
{
id: '',
name: '',
locations: [{ id: '', city: '', division: '', street: '' }],
},
],
},
],
}
convert it to
{
id: '',
name: '',
regions: {
id: '',
name: '',
districts: {
id: '',
name: '',
locations: { id: '', city: '', division: '', street: '' },
},
},
}
I already tried to convert it by using this code
const data = dataGetOrganization?.AllCountries
const result = Object.keys(data).reduce((acc, key) => {
acc[key] = {
...data[key],
_styles: {
root: { overflow: 'hidden' },
},
}
return acc
})
Try something like this:
var newObj = Object.assign({}, ...(array.map(item => ({ [item.key]: item.value }) )));

AssertionError [ERR_ASSERTION]: Mocks not yet satisfied: on using chaining with nock while testing Redux actions

I am trying to test an action in a React project with redux.
The test i am trying to do using Mocha,Enzyme is for a DELETE_USER action which is dispatched first on pressing a delete button and onSuccess of the action another action LOAD_ALL_USERS is dispatched which performs a get request.
Following is the code for test i tried , which gives the error as in the topic:
it('should call the /users endpoint with a user ID', (done) => {
const deleteUserResponse = {userId: 1337};
const mapActions = (actions) => ({
deleteActions: filterForAction(actions, 'DELETE_USER'),
loadAllUserActions: filterForAction(
actions,
'LOAD_ALL_USERS'
)
});
const loadAllUsersResponse =
[
{
id: 1337,
email: 'testuser9#some-company.com',
firstName: 'John',
lastName: 'Doe',
active: false
},
{
id: 1338,
email: 'adamsmith#mail.com',
firstName: 'Adam',
lastName: 'Smith',
active: true
}
];
const sampleApiSearchParams = {
locale: 'en-GB',
pageSize: 10,
sortBy: 'userId',
sortDirection: 'desc',
location: 'Zurich'
};
const sampleReactTableSearchParams = {
filtered: [
{id: 'userId', value: '1id'},
{id: 'userFirstName', value: 'fname'},
{id: 'userLastName', value: 'lname'},
{id: 'userEmail', value: 'maill'}
],
sorted: [{id: 'userId', desc: true}],
pageSize: 10
};
const scope = nock('http://localhost')
.delete('users/1337')
.reply(200, deleteUserResponse)
.get(uri=>uri.includes('users'),{...sampleApiSearchParams})
.reply(200, loadAllUsersResponse);
const store = mockStore(
{
stringResources: {
'deleteuser.confirm.title': 'User Delete Confirm',
'deleteuser.confirm.description':
'Are you sure you want to delete the user?',
'deleteuser.notification.message.success':
'is successfully deleted.'
},
userManagement: {
table: {
searchParams: sampleReactTableSearchParams
}
}
});
const actual = actions.deleteUser(1337)
store.dispatch(actual);
setTimeout(() => {
scope.done();
const {deleteActions, loadAllUsersActions} = mapActions(store.getActions());
expect(
deleteActions[1].meta['redux-pack/LIFECYCLE']
).toBe('success');
expect(deleteActions[1].payload).toEqual(
deleteUserResponse
);
//expect(loadAllUsersActions[1].payload).toEqual(loadAllUsersResponse);
done();
}, 50);
});
});
If i comment the 'scope.done()' the test passes, but http.get request is not getting called so the 'loadAllUsersActions' is undefined. How can i solve this , what is that i am doing wrong ?
Thanks in advance.

Create an array of objects with specific types and keys from original array of objects

I have an array ob object
const myDailyRutine= [
{
createdLetter:
date: "2018-10-12T05:44:44.553216+00:00"
user: {username: "lady-gaga"}
},
{
commentedEmail:
date: "2018-10-12T05:44:44.553216+00:00"
user: {username: "la-gaga", display_name: "La Gaga"}
},
{
commentedEmail:
date: "2018-10-12T05:44:44.553216+00:00"
user: {username: "maira-ter", display_name: "Ma Ter"}
}
];
I want to map over the array of objects and add a key 'type' to each event to identify what type of event it is 'createdEmail || createdLetter`
I tried a couple of things such as pick from lodash but I'm not getting the results I want.
How may I achieve this?
Lets try firs first iteration - map method will detect if object has only one property and assign it to new created type property:
const myDailyRutine = [{
createdLetter: {
date: "2018-10-12T05:44:44.553216+00:00",
user: {
username: "lady-gaga"
},
},
},
{
commentedEmail: {
date: "2018-10-12T05:44:44.553216+00:00",
user: {
username: "la-gaga",
display_name: "La Gaga"
},
},
},
{
commentedEmail: {
date: "2018-10-12T05:44:44.553216+00:00",
user: {
username: "maira-ter",
display_name: "Ma Ter"
},
},
},
]
const getValueOfFirstProperty = obj => {
const keys = Object.keys(obj)
if (keys.lenght > 1) throw new RangeError("Expected only one keys")
return keys[0]
}
console.log(
myDailyRutine.map(rutine => {
rutine.type = getValueOfFirstProperty(rutine)
return rutine
})
)
And lets try some OOP approach
const myDailyRutine = [{
createdLetter: {
date: "2018-10-12T05:44:44.553216+00:00",
user: {
username: "lady-gaga"
},
},
},
{
commentedEmail: {
date: "2018-10-12T05:44:44.553216+00:00",
user: {
username: "la-gaga",
display_name: "La Gaga"
},
},
},
{
commentedEmail: {
date: "2018-10-12T05:44:44.553216+00:00",
user: {
username: "maira-ter",
display_name: "Ma Ter"
},
},
},
]
class Rutine {
constructor(type, rutine) {
this.type = type // not necessary as we have got instance of CommentedEmail or CreatedLetter
Object.keys(rutine[type]).forEach(key => this[key] = rutine[type][key])
}
}
class CommentedEmail extends Rutine {
constructor(rutine) {
super('commentedEmail', rutine)
}
}
class CreatedLetter extends Rutine {
constructor(rutine) {
super('createdLetter', rutine)
}
}
const rutine = rutine => {
switch (Object.keys(rutine)[0]) {
case 'commentedEmail':
return new CommentedEmail(rutine)
case 'createdLetter':
return new CreatedLetter(rutine)
}
}
console.log(
myDailyRutine.map(rutine)
)

Update state using nested map es6

My state has an array of objects that also contains an array of objects.
var state = {
prop1: null,
categories: [
{
categoryId: 1,
tags: [
{
tagId: 1,
name: 'AA11',
status: true,
},
{
tagId: 2,
name: 'AA22',
status: false,
}
]
},
{
categoryId: 2,
tags: [
{
tagId: 1,
name: 'BB11',
status: true,
},
{
tagId: 2,
name: 'BB22',
status: false, // let's say i want to toggle this
}
]
},
]
};
I have an action that will toggle a status of a tag. This action will receive parameters categoryId and tagId.
So far I've come up with this but it doesn't work
return {
...state,
categories: state.categories.map((category) => {
category.tags.map(tag => (
(tag.tagId === action.tagId && category.categoryId === action.categoryId) ? {
...tag,
status: !tag.status,
} : tag));
return category;
}),
};
I finally fixed the map code.
return {
...state,
categories: state.categories.map(category => ((category.id === action.categoryId) ?
{
...category,
tags: category.tags.map(tag => (tag.id === action.tagId ? {
...tag, status: !tag.status,
} : tag)),
} : category)),
};

Resources