This is my code and I am trying to change value of object in packs object. But when I type it, Javascript somehow changes all three different objects, that have nothing in common. And this is the only line that changes packs, rest should stay the same, but it's all changing with this line. How?
console.log(packs[usedPack].levels[level].bestBy) //null
console.log(defaultPack.levels[level].bestBy) //null
console.log(mainPacks[usedPack].levels[level].bestBy) //null
packs[usedPack].levels[level].bestBy = nameTyped; //this changes values in three different objects
//packs[usedPack].levels[level] = nameTyped; //if I type like this, this does change only original object, rest stays the same
console.log(packs) //nameTyped
console.log(defaultPack) //nameTyped
console.log(mainPacks) //nameTyped
Edit: It was indeed problem with referencing. I was using constructor function and this function needed to deep copy complex objects. I was checking values and I used multiple loops to copy all values from objects, but it didn't work properly. I've changed all of this to JSON.parse(JSON.stringify()), and it's working now. Thanks for help.
The issue here seems like you're assigning some object by its reference.
In javascript, if you have two objects and you assign them like
a = b;
Now whenever you will change b, a will also be changed. To avoid this we do deep clone using the spread operator
// this now does not reference to b but clones it
a = {...b}
In your code, you might be assigning some objects like this. a=b
Maybe you're assigning packs, defaultPack, and mainPacks using some same object.
Updated
#David pointed out one thing and that is if you are having some complex structure (like objects within object) and then you clone it using spread operator, the inner objects will still reference the same object.
To resolve this, for easiness you can use lodash deepclone function
const clonedeep = require('lodash/clonedeep');
const deepClonedObject = clonedeep(originalObject);
This will deep clone and even if the objects are nested they won't refer to the same object.
I am trying to return the value under the key 'str' in an Object but I am having trouble accessing the value.
This is what is returned in the console:
Currently I am using a map function to go over the array and just return the _str value like so:
let idx = currentArray.map(function(x) {
return x._id._str;
});
However it is still returning the value as an object. How can I get just the value of the _str key?
Here is the full array without specifying the id field. This is what is returned if you jsut return 'x' in the map function.
You've clarified that the screenshot is of x._id. So to access _str, you'd use x._id[0]._str: The _str property is in the object referenced by the 0 property (the first entry in the array x._id refers to).
Note that in general, _-prefixed properties are meant not to be accessed by code outside the code responsible for the objects in question. You don't seem to be responsible for them, so accessing those properties is likely to make your code rely on undocumented properties that may change in the next "dot" release of whatever lib you're using. It's just convention, but it's a very common convention.
If you right click on the property, most browser consoles offer the ability to copy property path.
Based on this SO post and the docs, it appears that you can probably use x._id.str.
If I understand correctly, you are receiving the str value but it is an object instead of the string literal. In other words, you are getting _str: "598..." instead of "598....". A possible solution would be to use the mongo javascript function to convert the str value to a string.
In your case, I think something like return x._id.str; may work as _id is a MongoID.ObjectID.
I've also linked the documentation below for reference.
https://docs.mongodb.com/manual/reference/method/ObjectId/
Here's a relevant SO answer as well: Convert ObjectID (Mongodb) to String in JavaScript
I think you should write x[_id]._str because _id is one of the array objects.
If I run the following code, the length does not change:
console.log(files.length);
_.pull(files, [files[0], files[1]]);
console.log(files.length);
where files is an Array object. Shouldn't pull definitely find matches to remove given that I'm constructing its second arguments with values directly from the array?
for some reason trying to change the length property or doing anything that would cause the engine to implicitly change the length, such as calling files.splice, will throw a RangeError
Why not create a new array, using without() to remove the unwanted files?
var newFiles = _.without(files, files[0], files[1]);
I don't think you should pass in an array of values you want to 'pull'. The documentation suggests they should be separate arguments like so:
_.pull(files, files[0], files[1]);
https://lodash.com/docs#pull
I have two JSON stringified objects,
var first='{"AdmissionId":254625,"PhysicianId3":null,"VerbalStartOfCareDate":"","PhysicianId2":null,"LatestStatusCode":"A01","ReferralSource":97664,"PhysicianId1":97670,"$id":"2","LatestAdminSetId":90,"LastModified":"2015-03-16T10:13:55.827","AdmitDate":"2015-03-01T00:00:00","TeamId":153,"ProspectAdmitDate":null,"TerminationDate":null,"PatientId":154112,"PatientStatus":[{"Notes":null,"PpsTherapyVisits":null,"SyncEpisodes":null,"StatusCode":"A01","StatusId":0,"PpsEpisodeNo":1,"StatusEndDate":null,"PrimaryDiagnosisId":870428,"Sequence":2,"PpsAssessDate":null,"PatientId":154112,"Acuity":"Pend","SyncStatus":4,"LastModified":null,"BranchId":null,"PpsAssessRfa":null,"PrintDischargeSummary":null,"OasisMatchingKey":null,"PpsScicOverride":null,"PpsKnownLupa":null,"DataSetId":26,"AdminSetId":90,"MsaCode":"50094","GenerateFinalClaimOnly":null,"PpsEpisodeNoModified":"N","AssociatedFacilityRoleId":null,"ClassEndDate":null,"PpsHippsCode":null,"PpsHippsValidity":null,"PatientClass":"HH","ClientId":0,"PpsAssessmentId":null,"StatusTime":null,"HpcanysCareLocation":null,"PpsHhrgId":null,"EpsHhrgId":null,"Id":0,"$id":"3","StatusDate":"2015-08-17T00:00:00","AdmissionId":254625,"PpsNrsSeverityId":null,"AssociatedFacilityId":null}],"CaregiverCode":"SP","ReferralSourceRoleId":33149,"ClinicalSetId":93,"PatientAdmissionCtiDef":null,"Id":0,"SnfIndicator":null,"ClientId":0,"AdmissionCode":null,"ProspectTermDate":null,"SyncStatus":2,"Sequence":1}';
var second = '{"AdmissionId":254625,"PhysicianId3":null,"VerbalStartOfCareDate":null,"PhysicianId2":null,"LatestStatusCode":"A01","ReferralSource":97664,"PhysicianId1":97670,"$id":"2","LatestAdminSetId":90,"LastModified":"2015-03-16T10:13:55.827","AdmitDate":"2015-03-01T00:00:00","TeamId":153,"ProspectAdmitDate":null,"TerminationDate":null,"PatientId":154112,"PatientStatus":[{"Notes":null,"PpsTherapyVisits":null,"SyncEpisodes":null,"StatusCode":"A01","StatusId":802577,"PpsEpisodeNo":1,"StatusEndDate":null,"PrimaryDiagnosisId":870428,"Sequence":1,"PpsAssessDate":null,"PatientId":154112,"Acuity":"Pend","SyncStatus":2,"LastModified":"2015-03-16T10:11:26.857","BranchId":null,"PpsAssessRfa":null,"PrintDischargeSummary":null,"OasisMatchingKey":null,"PpsScicOverride":null,"PpsKnownLupa":null,"DataSetId":26,"AdminSetId":90,"MsaCode":"50094","GenerateFinalClaimOnly":null,"PpsEpisodeNoModified":"N","AssociatedFacilityRoleId":null,"ClassEndDate":null,"PpsHippsCode":null,"PpsHippsValidity":null,"PatientClass":"HH","ClientId":0,"PpsAssessmentId":null,"StatusTime":null,"HpcanysCareLocation":null,"PpsHhrgId":null,"EpsHhrgId":null,"Id":0,"$id":"3","StatusDate":"2015-03-01T00:00:00","AdmissionId":254625,"PpsNrsSeverityId":null,"AssociatedFacilityId":null}],"CaregiverCode":"SP","ReferralSourceRoleId":33149,"ClinicalSetId":93,"PatientAdmissionCtiDef":null,"Id":0,"SnfIndicator":null,"ClientId":0,"AdmissionCode":null,"ProspectTermDate":null,"SyncStatus":2,"Sequence":1}';
I need to remove the following properties from the above mentioned JSON objects and the result of that should be compared:
I used underscore's _.omit () functionality it removed only the outer collection property but it failed to remove the inner collection property
eg: PatientStatus.StatusId in the above JSON
I also tried using delete keyword of javascript it is working, but is there any better way to do it ?
Try to JSON.parse the string, and then delete the property you want to remove..
JS Delete - Mozilla MDN
what's the best way in JavaScript to store values in an assoziative array? I tried a lot of things and it always brakes somehow.
I tried something like:
var test = [];
for(var prop in json) {
test[prop] = json[key];
}
this works and i get a cool array then i can actually use. However calling test.length gives me 3 when there should be 10 items, it sometimes gives me 0 when there should be at least 8 items.
What do i do wrong? What's the best way to go here to get an assoziative array going which i can use properly like in Java?
Everything is an object in JavaScript. foo['bar'] is the same as foo.bar. Array is just an object with some predefined methods that let it emulate what you would call a numeric array in PHP or just an array in almost any other language. JavaScript objects work like associative arrays in PHP. The general non-PHP name for it is hash.
So, to address your problem with length, it is a predefined property of an array object. Using it on an object that isn't an array will not give you the results you are expecting. To count the number of properties in an object, you can use
Object.keys(obj).length
in modern browsers. keys() function gets an array of keys from a hash, so it will have a correct length property.
If you wish to support older browsers, you have to iterate through object properties and count them manually. Be aware that for (var prop in json) will also iterate through the properties of every object in the prototype chain, so you might want to check if a property is object's own property using hasOwnProperty() method.