Angular - Can't find value inside array - arrays

Good day everyone, I'm currently having problems using find for array.
Code: https://codeshare.io/EBoBEX
On line 80 is the code I'm unable to make work. Line 69 has a similar function but it works.
Error message:
ERROR TypeError: Cannot read property 'customer_fullname' of undefined
I am basically trying to enter the value into myForm. I am using mongodb and this is what is in the document:
1. _id:6114e3c1c5934f0fc8da2156
2. fullname:"John Pearson"
3. email:"john#gmail.com"
4. address:"Yishun street 69 Blk 420"
5. user_id:"61003363e8ded0257c63592a"
I used user_id: this.authService.getUserID() because after getting the user id from my auth service, I put it into myForm as user_id which I then try to use to find the fullname from my customers as the user_id value is the same as the _id for my users.
When I do console.log(this.customers); it shows the following:
[{…}] 0: address: "Yishun street 69 Blk 420" email: "john#gmail.com" fullname: "John Pearson" user_id: "61003363e8ded0257c63592a" _id: "6114e3c1c5934f0fc8da2156" [[Prototype]]: Object length: 1 [[Prototype]]: Array(0)
What I'm trying to do is find from the customers array based on the user_id, sorry if I was unclear
Any help will be appreciated, thank you so much in advance!

if you use ReactiveForms use formControlName
<select id='name' name='name' formControlName="user_id"
(change)="selectChangeHandler($event)">
To give value to a FomControl in a FormGroup use setValue to give it value
this.myForm.value.id = this.selectedId;
//really I don't know if is user_id or id
this.myForm.get('id').setValue(this.selectedId);
Always you can get a property you can make it two steps:
this.myForm.value.customer_fullname =
this.customers.find(x=>x.user_id===this.myForm.value.user_id)
.customer_fullname;
const customer=this.customers.find(x=>x.user_id===this.myForm.value.user_id)
this.myForm.get('customer').setValue(
customer?customer.customer_fullname:null)
If all the values are related to the element of the array, you can use an unique field, then, in submit you can simple use the element found it: "customer"

Related

How can you filter out data based on their id?

So i kinda have to filter out my username from the given data so that you'll find the username that matches with the post but i don't really understand the role of the "[0]". Can anybody expain for me? Thank you so much!
This is my js:
<span className="postUsername">
{Users.filter((u) => u.id === post?.userId)[0].username}
</span>
This is my data:
export const Users = [{
id: 1,
profilePicture: "assets/person/1.jpeg",
username: "Safak Kocaoglu",
}
...
export const Posts = [{
id: 1,
desc: "Love For All, Hatred For None.",
photo: "assets/post/1.jpeg",
date: "5 mins ago",
userId: 1,
like: 32,
comment: 9,
}
...
First of all, in that case you are expecting to get a single user and show the username which is the post userId. Filter will return you an array of the user matching the condition we gave. For the array here you are picking first element of that array with [0]. Here we want to have a single user so best way is to use find(), this will give us a single result.
If you want to have the username of the specific user (post.userId), the code will be like this:
{Users.find(u=> u.id === post?.userId).username}
So, filter() function is used for getting array result of matching condition and here with [0] you are picking the first element of the array. Instead of that if you use find() function you will get a single object.

Inserting encapsuled object in firestore and goods practices

I have a question about to insert object in firestore in angularfire:
My object Person.ts
name: String
age: Number
//--constructor--
//--getters and setters--
if I do this, insert ok: (BUT is this good practice?)
[person.component.ts]
this.db.collection("person").add({
name: this.person.$nome,
age: this.person.$email
})
...
but if I try:
[person.component.ts]
this.db.collection("person").add({
Person: this.person
//or this this.person
})
I get this error in browser console:
Function DocumentReference.set() called with invalid data. Unsupported field value: a custom Person object (found in field Person)
at new FirestoreError (error.js:149)
at
Firestore only accepts a JavaScript object embedded within a document if it is a “pure” object, this means you can't use custom objects while coding with TypeScript.
Change your code to:
this.db.collection("person").add(Object.assign({}, this.person));

How to set the key name on an array in Angularfire

I am creating arrays using Angularfire but I am unable to set the key name. Firebase is automatically giving me a cryptic key (eg Jm9vLy8Lye-KS35KsmL) but I would like to set it myself to something more meaningful. It is unclear how I do this in Angularfire. I am using the $add method on $firebaseArray:
var firebaseRef = new Firebase("https://firebase_location");
$scope.messages = $firebaseArray(firebaseRef);
$scope.messages.$add(
{
FirstName: patient.FirstName,
LastName: patient.LastName
}
).then(function(firebaseRef) {
var id = firebaseRef.key();
});
The data is stored fine and I can see it on my dashboard. However, id is always a cryptic firebase value. I would love to be able to set it myself to something meaningful. In my case the individual patient's ID would be meaningful...
Any thoughts?
Thank you!
Thanks for the response.
I found that the child function will do what I need. I first specify the child and then set it.
var patient_child = firebaseScreenRef.child(patient.PatientId);
patient_child.set(
{
FirstName: patient.FirstName,
LastName: patient.LastName,
});
Adding an item to a firebase array make firebase define a unique id for you. If this is not what you want, I think you can try getting the "messages" object with $firebaseObject, instead of getting just the list with $firebaseArray. Then you will be able to edit your object in js, in order to add your items to the messages collection. In this way you can use the id that best suits your needs. Finally, you have to $save() your entire object. Look here: https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebaseobject
Hope this helps.
For your question, I found an explanation. You don't need to use firebaseObject, you should use ref directly:
var ref = new Firebase(FURL);
createProfile: function(id ,user) {
var profile = {`enter code here`
name: user.name,
email: user.email,
gravatar: get_gravatar(user.email, 40)
};
var profileRef = $firebaseArray(ref.child('profile').child(id));
return ref.child('profile').child(id).set(profile);
},
In the code, I use ref to reference my URL. With profileRef, I created a child profile and I added id for the profile. Afterwards, I use ref directly to set the value profile for the id that I want. You see, it is very easy.

Underscore collection pluck returning undefineds [duplicate]

Hi im trying to output every "lat" field from my collection. However anything i do returns the right number of results but they all say undefined, the data is definitely there and the names are definitely right. I've tried using pluck and _.each with a get inside the function and all it ever says is undefined.
This is the current method im trying
var ccLocal = window.router.carsCollection;
_.each(ccLocal.models, function(model) {
console.log(model.lat);
})
logging ccLocal returns the entire collection with all its data so its definitely there. What am i doing wrong?
Using model.get("lat") also fails.
Using console.log(ccLocal.at(0).attributes); returns this
Object {unitID: "03_Cow_30", positionHistory: Array[1]}
positionHistory: Array[1]
0: Object
estimatedSpeed: "39"
isToday: false
lastSoundFileName: "F11"
lastSoundRange: "11"
lastSoundTime: "2008-10-29 20:38:25"
lat: "51.466227"
long: "-0.491647"
minutesAgo: 1016726
status: "1"
time: "2011-07-13 16:03:37"
__proto__: Object
length: 1
__proto__: Array[0]
unitID: "03_Cow_30"
__proto__: Object
Ah, so your model attributes data structure is not what everyone thought. Based on your attributes structure, you need something like this. It's a bit fragile due to assuming positionHistory is an array with at least one element, but that's where your data is.
var ccLocal = window.router.carsCollection;
_.each(ccLocal.models, function(model) {
console.log(model.get('positionHistory')[0].lat);
})

Duplication localStorage data using backbone.js + backbone.localStorage.js

I'm using backbone + backbone.localStorage to persist my data, and I get a wrong behavior:
I've got a model settings with one attribute called user
Settings = Backbone.Model.extend({
localStorage : new Backbone.LocalStorage('settingsStore')
});
var settings = new Settings();
settings.set({user: 'USERNAME'});
settings.save();
After this code if I output the settings.attributes data in weinre I get the following:
settings.attributes
Object
id: "3ac78cfb-ad60-1ab8-8391-f058ae9bfcfb"
user: "USERNAME"
__proto__: Object
Then I save the model to the localStorage, clear, and fetch it again:
settings.save();
settings.clear();
settings.fetch();
And the problem is that if I output the settings.attributes, now this attributes are stored inside a nested object:
settings.attributes
Object
0: Object
id: "3ac78cfb-ad60-1ab8-8391-f058ae9bfcfb"
user: "USERNAME"
__proto__: Object
__proto__: Object
And the problem is when I set the user name again in order to modify, a new attribute is added like this:
settings.attributes
Object
0: Object
id: "3ac78cfb-ad60-1ab8-8391-f058ae9bfcfb"
user: "USERNAME"
__proto__: Object
user: "NEWUSER"
__proto__: Object
And if I save this model, and fetch it again I get 2 new objects on the attributes... and it keeps growing each time.
The answer to the question given by fguillen link gives the correct answer to this problem.
You just need to create the model object with a hardcoded "ID" if you want to save it correctly.
After doing this:
var settings = new Settings({ id: 1 });
The save() and fecth() methods are working correctly. Obviously you have to take care not repeating 2 ID's...

Resources