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

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.

Related

Javascript for of loop errors

this is the file I'm using
[
{
"id": 1,
"name": {
"first": "Paige",
"last": "Bools"
},
"birthDate": "1995-02-04T07:34:45Z",
"contact": {
"phone": "8989068955",
"email": "pbools0#webmd.com"
},
"address": {
"street": "476 Veith Parkway",
"city": "Cuamba",
"country": "Mozambique"
},
"accessCount": 776,
"isManager": false
},
{
"id": 2,
// rest of json
}
]
Bunch of users all there.
My requirement is like this:
use a for-loop to iterate over the items in users
concatenate the first name and last name and assign to a name variable
call console.log() with the name variable
The function doesn't need to return anything.
I wrote my function like this. But its not working
function formatNames() {
for (name of users)
var name = users.name.first + users.name.last;
console.log(name);
}
formatNames();
Do u guys see any problem in this function?
The users array doesn’t have a name property, so users.name.first and users.name.last aren’t going to work.
The for loop is iterating the items in the array, not the names in the array. You can call the variable “name” if you want, but that’s not what it represents and will cause confusion.
Each time through the loop your name variable represents a user. So (leaving the loop variable named “name”) you’d need: name.name.first.
If you rename the loop variable to “user” it will make more sense:
for (const user of users) {
// do stuff with user.name.first
}

creating a variable to hold information that loads through another variable

Hard to explain in the title but my question is this:
I am using leaflet to create a map. Some information will be very repetitive, so I want to create variables to hold that information. I'm having trouble making the variables connect to eachother properly though to display properly. Is this possible? see code below to see what I mean. All the code works fine if I input the individual data for the variables (the lat/lng) I'm just not sure how to call the data from the somePlace variable into the food variable.
Example:
var somePlace = [{
"name": "name",
"address":"address"
"lat": "",
"lng": "",
}];
var anotherPlace = [{
"name": "name",
"address":"address"
"lat": "",
"lng": "",
}];
var food = [
{
"name": name.somePlace,
"address": address.somePlace,
"lat": lat.somePlace,
"lng": lng.somePlace,
"details": "info unique to this object"
},{
"name": name.anotherPlace,
"address": address.anotherPlace,
"lat": lat.anotherPlace,
"lng": lng.anotherPlace,
"details": "info unique to this object"
}
];
then in the main JS, this data is called in like so.
for (var i = 0; i < somePlace.length; ++i) {
var place = somePlace[i].details;
var sP = L.marker([somePlace[i].lat, somePlace[i].lng], {
icon: myIcon
})
.bindPopup(place);
There is a misconception in your code. Looks like you want the food variable to contain information from somePlace and anotherPlace.
somePlace and anotherPlace are arrays of objects which means that you can access their elements via an index such as somePlace[i] where i is an integer (as described in the loop you've pasted).
When you get an object from the array, (eg. the first object with var myElement = somePlace[0], because arrays in JavaScript are zero indexed), you can then access the object's properties via what is called dot notation.
So in your example, if you want to use the first element of the somePlace array and the first element of the anotherPlace array to form the food variable, you can do something like:
var food = [{
"name": somePlace[0].name,
"address": somePlace[0].address,
"lat": somePlace[0].lat,
"lng": somePlace[0].lng,
"details": "info unique to this variable"
},{
"name": anotherPlace[0].name,
"address": anotherPlace[0].address,
"lat": anotherPlace[0].lat,
"lng": anotherPlace[0].lng,
"details": "info unique to this variable"
}];
The objects are in key - value pairs, so for example in the case of eg. var foo = { name: "Mary" }, name acts as the key, Mary as the value and foo is the variable declaration, in this case an object.
If you expect repetitive structure, one way to solve this would be through the use of constructors.
// constructor
function Place(name, address, lat, lng, detail) {
this.name = name;
this.address = address;
this.lat = lat;
this.lng = lng;
this.detail = detail;
}
// declare empty array
var food = [];
// instance of Place
var somePlace = new Place('The Greatest Place', '1234 Main St', '45', '-17', 'Unique detail');
food.push(somePlace);
// another instance
var anotherPlace = new Place('Another Place', '777 High St', '47', '-18', 'Another unique detail');
food.push(anotherPlace);
// objects stored in your array
console.log(food);
// access specific object and property
console.log(food[0].name);

Access nested Immutable Map property

I'm learning Immutable.js. I have an object that when called:
myObj.get('people')
returns the following:
[
{
"name": "John Stevenson",
"country": "Sweden"
},
{
"name": "John Silva",
"country": "Colombia"
},
{
"name": "John Van der Bier",
"country": "Holland"
},
{
"name": "John McDonald",
"country": "Scotland"
}
]
I'm trying to get inside this object so I can only see country:
myObj.getIn(['people', 'country']) // undefined
What am I missing?
The problem with you're code is that the result of getIn(['people', 'country']) is attempting to access the country property of people, which is an array and doesn't have a property named country. It seems like want to loop over people and build an array of their countries, which you can do with map:
var countries = myObj.get('people').map(person => {
return person.country
})
The previous answer will return an array. If you are truly wanting to use Immutable you should use
import { fromJS } from 'Immutable';
const immutableObj = fromJS(myObj);
//map() or forEach() here
var countries = immutableObj.map(person => {
return person.get('country');
})

Can a JSON array contain objects of different key/value pairs?

Can a JSON array contain Objects of different key/value pairs. From this tutorial, the example given for JSON array consists of Objects of the same key/value pair:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}
If I want to change it to have different key/value pairs inside the JSON array, is the following still a valid JSON?
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
Just want to confirm this. If so, how can I use JavaScript to know if the JSON "example" field contains the first homogeneous objects or the second heterogeneous objects?
You can use any structure you like. JSON is not schema based in the way XML is often used and Javascript is not statically typed.
you can convert your JSON to a JS object using JSON.parse and then just test the existence of the property
var obj = JSON.parse(jsonString);
if(typeof obj.example[0].firstName != "undefined") {
//do something
}
It doesn't matter you can mix and match as much as you want.
You could just test it
typeof someItem.example !== 'undefined' // True if `example` is defined.
It's perfectly valid JSON. Personally I prefer this syntax better, because it reads easier:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
As to answer your second question, you can read data from a JSON string by using var data = JSON.parse(datastring);. Then simply use it by calling data.property.secondlevel. Any variable can be an object, array, string or number, allowing for nested structures.
You are free to do what you want with the contents of the array. Jus remember about this before you try to iterate an access properties of each item in your array.
one thing: you won't be able to deserialize this to anything else than an array of object in your server side, so don't have surprises later.
as a hint, maybe you could include a common field in the objects specifying the "type" so later is easy to process.
var array = [{"type":"fruit", "color":"red"},
{"type":"dog", "name":"Harry"}];
var parser = {
fruit:function(f){
console.log("fruit:" + f.color);
},
dog: function(d){
console.log("dog:"+d.name);
}};
for(var i=0;i<array.length;i++){
parser[array[i].type](array[i]);
}

JSON Object to be Stored into an Array

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

Categories

Resources