JSON Object to be Stored into an Array - javascript

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];
}

Related

Destructuring props dynamically React

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"

Update properties of an object of an array

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.

creating multiple javascript objects using a loop that reads from json data

I am trying to create a number of Javscript objects at once by using a loop through json data. I'm having trouble finding a way to do this and if someone could take a look at the below code and suggest the best way of looping through the json data and creating the objects that would be great.
// Create Test Constructor
function Test(name, age, address) {
this.name = name;
this.age = age;
this.address = address;
}
// Create Test Object
let test1 = new Test("name[0]", age[0], "address[0]");
//json data from a seperate .json file
{
"Tests": [
{
"name": "First Person",
"age": 20,
"address": "New York"
},
{
"name": "Second Person",
"age": 21,
"address": "The World"
},
{
"name": "Third Person",
"age": 22,
"address": "The Universe"
}
]
}
Thanks
If you just need plain objects:
const { Tests } = JSON.parse('//json data from a seperate .json file');
Now Tests should be an array of Test objects.

While retrieve a model by ID from a Backbone.js collection returning undefined

I'm trying to get a model from a collection by it's ID and display in view. After instantiating a model, I'm using the methods like get(), at() but it's returning undefined.
My collection:
[
{
"id": "1",
"firstname": "Abc",
"lastname": "Xyz"
},
{
"id": "2",
"firstname": "Klm",
"lastname": "Opq"
},
{
"id": "2",
"firstname": "rst",
"lastname": "Yvw"
}
]
Instantiation:
var persons = new PersonCollection();
console.log(persons.get(1)); // undefined
NOTE: I'm getting all the models in console (Not an issue). I want only to fetch a model by it's id name.
fetch is async so you need to place your code inside success callback
persons.fetch({
success: function() {
console.log('Now I have something: ', persons.get(1))
}
})
console.log('Nothing here: ', persons.get(1))
BTW to fetch single model by id you could use Model#fetch instead

Json in sessionStorage with array of objects

Hi all I am creating a Json and adding it to Sessionstorage as follows
<script type="text/javascript">
function addMoreProducts() {
if (sessionStorage.getItem("empData") === null) {
var empInformation = {
"employees": [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
]
}
var x = JSON.stringify(empInformation);
sessionStorage.setItem("empData", x);
}
else {
if (sessionStorage.getItem("empData") != null) {
var empInformation = {
"employees": [
{ "firstName": "John1", "lastName": "Doe1" },
{ "firstName": "Anna1", "lastName": "Smith1" },
{ "firstName": "Peter1", "lastName": "Jones1" }
]
}
var v = sessionStorage.getItem("empData").toString();
var jParse = JSON.stringify(v);
var jparse1 = JSON.stringify(empInformation);
var arrayOfObjects = [jParse, jparse1];
}
var vparse = JSON.stringify(arrayOfObjects);
var vparse1 = JSON.parse(vparse);
sessionStorage.removeItem('empData');
sessionStorage.setItem("empData", vparse);
}
}
</script>
But when I retrieve the data from sessionStorage after assigning data this is not giving me proper json format can some one help me. This is the format I am getting
"["\"{\\"employees\\":[{\\"firstName\\":\\"John\\",\\"lastName\\":\\"Doe\\"},{\\"firstName\\":\\"Anna\\",\\"lastName\\":\\"Smith\\"},{\\"firstName\\":\\"Peter\\",\\"lastName\\":\\"Jones\\"}]}\"","{\"employees\":[{\"firstName\":\"John1\",\"lastName\":\"Doe1\"},{\"firstName\":\"Anna1\",\"lastName\":\"Smith1\"},{\"firstName\":\"Peter1\",\"lastName\":\"Jones1\"}]}"]"
When I watch it in console. Also I am using restful service where my service holds a datatable as a parameter how can I pass this json object to that method as DataTable
This is actually a very wide discussed issue:
This is what is proposed by microsof in this article
If this function causes a JavaScript parser error (such as "SCRIPT1014: Invalid character"), the input text does not comply with JSON syntax. To correct the error, do one of the following:
Modify the text argument to comply with JSON syntax. For more information, see the BNF syntax notation of JSON objects.
For example, if the response is in JSONP format instead of pure JSON, try this code on the response object:
var fixedResponse = response.responseText.replace(/\\'/g, "'");
var jsonObj = JSON.parse(fixedResponse);

Categories

Resources