I have an array of objects and I need to update a few properties of a specific object inside the array and then run the findAndUpdateById call on it. I am trying to do this but its not updating and gives me an error of undefined name property. I guess I am not following the right procedure to update an update an object of javascript and because of this i need help.
Here is my array
let arr = [
{
"_id": "1234",
"customer": {
"firstName": "John",
"lastName": "Doe",
"email": "johndoe#gmail.com",
"address": "123 Caroline Street"
}
}
]
Now I am recieving parameter like this that i need to update in my object
let ctx = {
"params": {
"changeObject": {
"firstName": "Ali",
"email": "ali#gmail.com"
}
}
}
Given: "I am getting the array of object by making .find call against id and there will be only one customer object in the received array"
// Given
let arr=[{"_id":"1234","customer":{"firstName":"John","lastName":"Doe","email":"johndoe#gmail.com","address":"123 Caroline Street"}}];
let ctx={"params":{"changeObject":{"lastName":"Ali"}}};
arr[0].customer = Object.assign(arr[0].customer, ctx.params.changeObject);
console.log(arr);
I think you were using different properties changePayload and changeObject.
You may want to use the spread operator and map for this as well.
let arr = [
{
"_id": "1234",
"customer": {
"firstName": "John",
"lastName": "Doe",
"email": "johndoe#gmail.com",
"address": "123 Caroline Street"
}
}
];
let ctx = {
"params": {
"changePayload": {
"firstName": "Ali",
"email": "ali#gmail.com"
}
}
}
arr = arr.map( data => ({
...data,
customer: {...data.customer, ...ctx.params.changePayload}
}) );
console.log( arr );
NOTE: This will change all objects in your array, but that is what you were asking for.
Related
Imaging we have a props, a really large object:
{
"firstname": "John",
"lastname": "Doe",
"age": 11,
"mode: "expert",
"website": "stackoverflow.com"
"protocol": "https",
"job": "dev",
"env": "main",
..... and a lot of key-values pairs coming
}
What usually we are calling to create "component variables":
let {firstname,
lastname,
age,
mode,
website,
protocol,
job,
env
...and a lot of "keys" as variable names} = props
// so we can call variable, {age} for example
I don't like to type all these variables in let {}, do we have something dynamic to declare "all keys" dynamically? I am not sure it's possible.
Of course I can use {props.firstname} in my code.
There is a way to create dynamically variables in let {} scope?
Any help is appreciated.
You can get all keys dynamically by Object.keys
const obj = {
"firstname": "John",
"lastname": "Doe",
"age": 11,
"mode": "expert",
}
const keys = Object.keys(obj)
console.log(keys)
//from these keys, you can get values based on your needs
//the first key value is `firstname`
//the first value is `John`
console.log(keys[0], obj[keys[0]])
Do you want to use (destructure) some props, and leave the rest in another object?
You can do that with i.e.
let testobject = {
"firstname": "John",
"lastname": "Doe",
"age": 11,
"mode": "expert"
}
const {firstname, lastname, ...verySmartFunc} = testobject ;
console.log(verySmartFunc);
//now your object is verySmartFunc,
//created with those keys you haven't destructured, and has next properties
{
age: 11,
mode: "expert"
}
If that's not what you're looking for and I misunderstood your question, I'd say you're already having props as an object with all those keys.
EDIT: Maybe this is what you're looking for, based on Nick Vu's answer.
const obj = {
"firstname": "John",
"lastname": "Doe",
"age": 11,
"mode": "expert",
}
const keys = Object.keys(obj)
let i = 0;
for (var key in keys) {
window[keys[i]] = obj[keys[i]];
i++
}
console.log(firstname); //result is "John"
I have a json file like below:
{
"users": [
{
"id": "person1",
"information": [
{
"first_name": "Mike",
"last_name": "Patty",
"address": ["address1","address2"]
},
{
"first_name": "Mike2",
"last_name": "Patty2",
"address": ["address1","address2"]
}
]
},
{
"id": "person2",
"information": [
{
"first_name": "Tom",
"last_name": "Jerry",
"address": ["address1","address2"]
},
{
"first_name": "Tom2",
"last_name": "Jerry2",
"address": ["address1","address2"]
}
]
}
]
}
I would like to iterate users and add each user's information to the API database. addInfo request requires: first_name, last_name and address (address is array). It is because I need to save response from information request for later use. I am pretty new to angular/typescript. So here is what I am trying to code so far:
Thank you in advance!
forkjoin need an array of observables, execute the observables, and, when all the onbservables are completed return the response of each one. So you should create this array of observables. For this, you convert your array "users" in an array of call API. For this you use "map" (is the "map of an array")
const addUsers$ = forkJoin(
User.map(x=>
//each "x" is in the way {id:..,information:{first_name:..,last_name:..,address:..}
this.APIservice.addInformation(
{
firstName: x.information.first_name,
lastName: x.information.last_name,
organizations: x.information.address
}
)).subscribe((res:any[])=>{
//in res[0] you has the response to the first call API,
//in res[1] you has the response to the second one
//...
})
Try flatMap
const addUsers$ = forkJoin(
Users.flatMap(user => user.information).map(info =>
this.APIservice.addInformation(
{
firstName: info.first_name,
lastName: info.last_name,
organizations: info.address
}
)))
);
I have a set of checkboxes that allow a user to check which roles to assign to a new user. I am able to filter back and get only the checkboxes that are actually checked, however, I am having trouble finding the best way to just return the "name" key of those checked checkboxes.
userToAdd.roles = this.roles.filter( (role) => role.checked );
Is there a way to use a reduce, or basically just say "role.name" in the filter so I don't return the entire object? I can do this with a for loop, but I'm curious if there is a better way to just return the name key as part of the filter?
This is how the object looks now, which is wrong:
{
"firstName": "sfsdfds",
"username": "fdsfsdf",
"lastName": "sdfsdfsdf",
"email": "dsfsdfdsf",
"roles": [
{
"ID": "ce97fb46-7e04-4a4f-b393-5a5492b558fb",
"name": "admin",
"checked": true
},
{
"ID": "e89bacd2-4140-46a1-9a2b-0f85aa9f9ca0",
"name": "offline_access",
"checked": true
}
],
"password": "pass"
}
This is how the object should look, in the roles array i just include the name, not the ID or checked keys:
{
"firstName": "testing",
"lastName": "testing",
"username": "testing",
"email": "testing",
"roles": [
"uma_authorization",
"offline_access"
],
"password": "pass"
}
you could map after filtering. i.e:
userToAdd.roles = this.roles.filter( (role) => role.checked ).map(role => role.name;
You can achieve this using array map() method and object destructuring like:
userToAdd.roles = this.roles.filter(({checked}) => checked).map(({name}) => name);
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Yes you can use reduce.
const data = {
"firstName": "sfsdfds",
"username": "fdsfsdf",
"lastName": "sdfsdfsdf",
"email": "dsfsdfdsf",
"roles": [
{
"ID": "ce97fb46-7e04-4a4f-b393-5a5492b558fb",
"name": "admin",
"checked": true
},
{
"ID": "e89bacd2-4140-46a1-9a2b-0f85aa9f9ca0",
"name": "offline_access",
"checked": true
},
{
"ID": "e89bacd2-4140-46a1-9a2b-0f85aa9f9ca0",
"name": "offline_access2",
"checked": false
}
],
"password": "pass"
}
let filtered = data.roles.reduce((acc, curr)=>{
if(curr.checked) {
acc.push({
name: curr.name
})
}
return acc;
}, []);
console.log(filtered);
.filter().map() would also works but with reduce you don't have to iterate over array twice.
If you have linq, this is another option:
userToAdd.roles = from(this.roles).where(role => role.checked ).select(role =>role.name).toArray();
You can also use this:
this.roles.filter( (role) => role.checked )[0].anyPropert;
I have 2 arrays. users and posts. posts contain a property "post_by" which is the id of one of the users. I need to match the user and push the first & last name into the post object as a new property. Goal is I need to display the name of the user that made the post in a table.
note* I can use javascript, jquery, linq.js or lodash.
fiddle with json
fiddle
var users = [
{
"id": "15e640c1-a481-4997-96a7-be2d7b3fcabb",
"first_name": "Kul",
"last_name": "Srivastva",
},
{
"id": "4cada7f0-b961-422d-8cfe-4e96c1fc11dd",
"first_name": "Rudy",
"last_name": "Sanchez",
},
{
"id": "636f9c2a-9e19-44e2-be88-9dc71d705322",
"first_name": "Todd",
"last_name": "Brothers"
},
{
"id": "79823c6d-de52-4464-aa7e-a15949fb25fb",
"first_name": "Mike",
"last_name": "Piehota"
},
{
"id": "e2ecd88e-c616-499c-8087-f7315c9bf470",
"first_name": "Nick",
"last_name": "Broadhurst"
}
]
var posts = [
{
"id": 1,
"status": "Active",
"post_title": "test title",
"post_body": "test body",
"post_by": "4cada7f0-b961-422d-8cfe-4e96c1fc11dd"
},
{
"id": 2,
"status": "Fixed",
"post_title": "test title two",
"post_body": "test body two",
"post_by": "79823c6d-de52-4464-aa7e-a15949fb25fb"
}
]
https://jsfiddle.net/zy5oe25n/7/
console.log($.map(posts, function(post){
var user = $.grep(users, function(user){
return user.id === post.post_by;
})[0];
post.first_name = user.first_name;
post.last_name = user.last_name;
return post;
}));
Here's a lodash approach:
_.map(posts, function(item) {
return _.assign(
_.pick(_.find(users, { id: item.post_by }),
'first_name', 'last_name'),
item
);
});
It's using map() to map the posts array to a new array of new objects (immutable data). It's then using find() to locate the user object, and uses pick() to get the properties we need. Finally, assign() adds the post properties to the new object that pick() created.
For good measure, using linq.js.
var userMap = Enumerable.From(users).ToObject("$.id");
posts.forEach(function (post) {
var user = userMap[post.post_by];
if (user) {
post.first_name = user.first_name;
post.last_name = user.last_name;
}
});
Note, we're using the builtin forEach() for arrays, linq.js is not needed for that part.
I am currently trying to store JSON stringified objects into an array so I will be able to add new elements as I go along:
function GetAllPatients(){
var patient = null;
var patients = [];
patient = { "FirstName": "Stephanie", "Gender": "Female", "Id": "P8401", "LastName": "BARRON", "Title": "Ms", "ConsultantId": "d10", "CurrentWardAdmissionName": "Non Admitted", "DOB": "/Date(1187650800000+0100)/", "HospitalAdmissionDate": "/Date(1294848066000+0000)/", "NHSNumber": "4646399561" };
patient = { "FirstName": "Joan", "Gender": "Female", "Id": "50434619", "LastName": "SMITH", "Title": "Mrs", "ConsultantId": "d1", "CurrentWardAdmissionName": "Non Admitted", "DOB": "/Date(513039600000+0100)/", "HospitalAdmissionDate": "/Date(1332242252817+0000)/", "NHSNumber": "9999999999" };
}
and also a switch case getPatientFromStore(pid) function which will retrieve a record by pid
How would I go about achieving this?
Is there any more information which I would require to help get me closer to a solution?
Basically, I'm in the middle of creating a web application which will allow offline local storage at a disconnected state, and also sync with a database on the server.
You can insert elements into an array by using push:
For example:
patients.push({
"FirstName": "Stephanie",
"Gender": "Female",
"Id": "P8401",
"LastName": "BARRON",
"Title": "Ms",
"ConsultantId": "d10",
"CurrentWardAdmissionName": "Non Admitted",
"DOB": "/Date(1187650800000+0100)/",
"HospitalAdmissionDate": "/Date(1294848066000+0000)/",
"NHSNumber": "4646399561"
});
As far as looking up by id, rather than an array, it would be better to use an associative array, like so:
var patients = {};
function addPatient(patient) {
patients[patient.id] = patient;
}
Then in your method to return a patient given the patient's id, you can do:
function getPatient(id) {
return patients[id];
}
This is useful if you're going to be looking up patients by their id all the time.
You could also use multiple indexes to access the same patient.
E.g. if you wanted to use NHSNumber as well as id you could do the following in the addPatients() function:
var patients = { };
var nhsNumberMap = { };
function addPatient(patient) {
patients[patient.id] = patient;
nhsNumberMap[patient.NHSNumber] = patient;
}
So you could also have another function:
getPatientByNHSNumber(nhsNumber) {
return nhsNumberMap[nhsNumber];
}