How to remove the inner properties from JSON object - javascript

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

Related

Use/advantage of Array Destructing?

I have recently moved to 'airbnb-base' eslint style-guide. There i am get an error when i try to reference the array elements with index eslint(prefer-destructuring).
eg
let a = {};
// get an error saying eslint(prefer-destructuring)
a.b = clients[0];
What is wrong with using accessing Array with index or how is using array destructuring better ?
Here is what AirBnB has to say about the need for these rules.
5.1 Use object destructuring when accessing and using multiple properties of an object. eslint: prefer-destructuring
Why? Destructuring saves you from creating temporary references for those properties.
5.3 Use object destructuring for multiple return values, not array destructuring.
Why? You can add new properties over time or change the order of things without breaking call sites.
The explanation for all the rules can be found in https://github.com/airbnb/javascript

How do I access the 'str' value in my 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.

Saving an element as a index in a object

I'd like to save a DOM element in a object. But not as a value, i want save it as a key of the object. But i think the core of javascript is not able to do that.
data={}
data[$('div#a')] = 'A';
data[$('div#b')] = 'B';
console.log(data[$('div#a')]); //return B
Do you know some way to save the element in a index object?
Imagine i have XXXXXX elements on my document. If i want to access to the element properties when some event happen on it i dont want to iterate XXXXXX elements to find it.
Why i don't use data of jquery for two reasons:
I want to do it on native javascript
I dont want another array to iterate separate data from the elementid
So the perfect way to do it was have only one object with the elements on the key to acces them easy. And if i want iterate them i only have to do for i in data
JavaScript objects will only accept strings as keys, and JS will use .toString() if you try to use anything else as a key, typically resulting in everything being stored under the (single) key "[object Object]".
Is there any reason you can't use $('#a').data() to store the data associated with that element directly on the element?
Failing that, assuming that every such element has an ID, just use the element ID as the object key.
NB: ES6 has a Map object which can use arbitrary keys, but that's only an experimental feature in current browsers. However even then you would have to use the actual element as the key rather than a jQuery wrapped $(element) object, since $('#a') !== $('#a') - you would have to use the exact same original jQuery object each time you access the map, not a newly constructed object.
Javascript objects only accept string as key.
So if you try to give key value other than string, javascript will internally call .toString() method of that object and use return value of it as key.
Object keys have to be stings.
You can use the data method to associate anything to the element:
$('div#a').data('name', 'A');
$('div#b').data('name', 'B');
console.log($('div#a').data('name')); //return B

How to convert the result of jQuery .find() function to an array?

What does jQuery .find() method return? a object OR a array list of objects?
If it returns an object which contain all the matched elements. How to convert this object to an array?
If it returns a array of elements, why $(xml).find("DATE").sort(mySortFunc); does not work, it seems the jQuery .find() returns an object which can not apply Javascript sort() method which is supposed to be applied on array.
Generally, I need to sort the objects find by $(xml).find("DATE") , but when I use sort function, it raised an error that the object can not be resolved.
The majority of jQuery methods returns a jQuery object, which can be accessed like it is an array (e.g. it has a .length attribute, elements can be accessed using the square bracket notation ([0]), and it supports some array methods (slice())).
jQuery has a method called toArray() which can be used to convert the jQuery object to a real array.
You can also use get() with no arguments to achieve the same effect (and save you a few key presses).
In future, you can checkout the jQuery API, and the return type for all jQuery methods is listed in the relevant documentation (e.g. for find(), the return type is "jQuery")
If you call .get() on a jQuery object without a parameter, it will return a regular array of DOM elements.
jQuery already acts like an array, and thus you can apply array like functionality to it.
Try to change
$(xml).find("DATE").sort(mySortFunc);
with
Array.prototype.sort.apply($(xml).find("DATE"), mySortFunc);
and you should get what you need

javascript object instantiation to include an array as one of the properties

I am trying to create an object which includes an array stPoints as one of its properties.
I am getting an error message saying that stPoints is undefined. What is the proper way to declare an array property within an object?
this is my code:
var temp={stName:"#states.stateid#",stPoints:[]};
This is correct. You must be referencing it incorrectly.
temp.stPoints
var temp={
'stName':"#states.stateid#",
'stPoints':[]
};
However, if the property name is a valid javascript identifier, as in this case, you should not have problem.

Categories