creating a variable to hold information that loads through another variable - javascript

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);

Related

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.

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
}

localStorage Array of Objects: Only push new object into array if unique

I have read through a number of Stack Overflow questions but none appear to be relevant to the problem I'm trying to solve.
I have an array of objects that I'm saving in localStorage which looks like this (this example includes just two):
[
{
"image": "http://example-image.jpg",
"restaurantName": "Elena's L'Etoile",
"parentLocation": "London",
"areaLocation": "West End of London",
"pageLink": "http://example-address1"
},
{
"image": "http://example-image2.jpg",
"restaurantName": "Pied a Terre",
"parentLocation": "London",
"areaLocation": "West End of London",
"pageLink": "http://example-address2"
}
]
Each time a user visits a page, data is pulled from the page, and a restaurant object is created which looks like this:
var restaurant = {"image": $image, "restaurantName": $restaurantName, "parentLocation": $parentLocation, "areaLocation": $areaLocation, "pageLink": $pageLink};
This is then stored pushed into the existing array of objects (above) with:
existingRestaurants.push(restaurant);
The problem is that if the user visits the same page twice, duplicate objects are pushed in the array. How can I ensure that only unique objects are pushed into the array?
Approaches I've looked into: using $.each, $.inArray, $.grep. I thought that the simplest way would be to loop through all the objects in the existingRestaurants array and compare the value of the "restaurantName" key with the corresponding value in the new restaurant object.
But I haven't been able to find anything else similar on Stack Overflow.
There's a few solutions you could use here. The first is to keep your current array of objects and scan them all for a duplicate restaurant name before inserting a new one. This would look something like this:
// assuming 'arr' is the variable holding your data
var matches = $.grep(arr, function(obj) {
return obj.restaurantName == $restaurantName;
});
if (matches.length) {
console.log('Duplicate found, item not added');
} else {
var restaurant = {
"image": $image,
"restaurantName": $restaurantName,
"parentLocation": $parentLocation,
"areaLocation": $areaLocation,
"pageLink": $pageLink
};
arr.push(restaurant);
}
Working example
Alternatively, and preferably, you could amend your data structure to be an object with the keys being the value which cannot be duplicated; in this case the restaurant names:
var arr = {
"Elena's L'Etoile": {
"image": "http://example-image.jpg",
"parentLocation": "London",
"areaLocation": "West End of London",
"pageLink": "http://example-address1"
},
"Pied a Terre": {
"image": "http://example-image2.jpg",
"parentLocation": "London",
"areaLocation": "West End of London",
"pageLink": "http://example-address2"
}
};
if (arr[$restaurantName]) {
console.log('Duplicate found, item not added');
} else {
var restaurant = {
"image": $image,
"parentLocation": $parentLocation,
"areaLocation": $areaLocation,
"pageLink": $pageLink
};
arr[$restaurantName] = restaurant;
}
Working example
How about an associative array? You'll have to select a key though:
var restaurant0 = {"image": "http://example-image.jpg", "restaurantName": "Elena's L'Etoile", "parentLocation": "London", "areaLocation": "West End of London", "pageLink": "http://example-address1" };
var restaurant1 = {"image": "http://example-image2.jpg", "restaurantName": "Pied a Terre", "parentLocation": "London", "areaLocation": "West End of London", "pageLink": "http://example-address2"};
var existingRestaurants = {};
existingRestaurants["id0"] = restaurant0;
existingRestaurants["id1"] = restaurant1;

document.getElementById and Value

I am new to Javascript and I would like to use the document.getElementById to show the value of items, in my example I would like to list the names printed in the var= btsFrontEnd ,but I am doing something wrong. Any help will be much appreciated.
Thank you.
Link to my Fiddle
var btsFrontEnd = {
"employee-1": {
"name": "Name One",
"phone": "1234567890",
"email": "blah#blah.com"
},
"employee-2": {
"name": "Name Two",
"phone": "1234567890",
"email": "blah#blah."
}
};
var btsemployees = {
employees:[
{
"name": "Name One",
"phone": "1234567890",
"email": "blah#blah.com"
},
{
"name": "Name Two",
"phone": "1234567890",
"email": "blah#blah.com"
},
{
"name": "Name Three",
"phone": "1234567890",
"email": "blah#blah.com"
},
{
"name": "Name Four",
"phone": "1234567890",
"email": "blah#blah.com"
},
{
"name": "Name Five",
"phone": "1234567890",
"email": "blah#blah.com"
}
]
};
//First argument is our data structure (an object or an array
//Second argument is a callback (logic we apply to our data structure)
$.each(btsFrontEnd, function (key, value) {
console.log(key); //Prints this object's keys
console.log(value); //Prints immediate values from this object
console.log(btsFrontEnd[key]);
console.log(value.name);
document.getElementById("names").innerHTML.value;// This is what I am referring to, I would like it to appear in the p id="names"
});
Here is the jsfiddle: http://jsfiddle.net/Ss2kk/7/
// Put names into an array
var employeeNames = [];
$.each(btsFrontEnd, function (employeeid, employee) { //first is the key or index, second argument is the value
// Check each element if it has name field
if (employee.name !== undefined) {
// Put its name into the array
employeeNames.push(employee.name);
}
});
// Join the array as comma seperated and put the content into `<p>` tag.
document.getElementById("names").innerHTML = employeeNames.join(",");
Inside your loop the key and value params represent the following values in the first iteration:
key
"employee-1"
value
Object { name="Name One", phone="1234567890", email="blah#blah.com"}
Since value is an object you can acces the name like this: value.name.
var names = document.getElementById( 'names' );
names.innerHTML = '';
$.each( btsFrontEnd, function( key, value ) {
names.innerHTML += value.name + '<br>';
});
All answers listed use jQuery, so I thought it'd be useful to add a pure javascript version. Two versions actually.
The first version uses Object.keys, which is relatively new compared to hasOwnProperty, which is used in the second version. This means the second version is compatible with more browsers.
Version 1:
// Declare variables
var keys, i, names = [];
// Get all keys in the btsFrontEnd object in an array. This is employee-1 and employee-2 in the example.
keys = Object.keys(btsFrontEnd);
// Loop over all keys
for(i = 0; i < keys.length; ++i) {
// Get the name of the employee via it's key and add it to the name array.
names.push(btsFrontEnd(keys[i]).name);
}
//Make one long string from the names with a comma as seperator, then put the string in the dom element.
document.getElementById("names").innerHTML = names.join(",");
Version 2:
// Declare variables
var key, names = [];
//Loop over all object properties
for(key in btsFrontEnd) {
// Check if the property is defined by you, and is not a standard Object property.
if(btsFrontEnd.hasOwnProperty(key)) {
names.push(btsFrontEnd[key].name);
}
}
//Make one long string from the names with a comma as seperator, then put the string in the dom element.
document.getElementById("names").innerHTML = names.join(",");

how to make an array name a variable in an object

var data = {};
$('.content').each(function(i){
var id = $(this).attr('id'),
level = $(this).attr('level'),
name = $(this).find('textarea').val(),
data2 = {
i:[
{
"id": id,
"level": level,
"name": name
}
]
};
$.extend(data, data2);
});
In the object data2 i want the array i to be an auto increasing number based on the .each. But it keeps naming it i.
data2 = {};
data2[i] = {
"id": id,
"level": level,
"name": name
};
Property names are treated literally in Javascript, whether or not there are any variables with that name.
However, you redefine the object on every iteration of the loop. Your code should probably look like this:
data2[i] = {
id: id,
level: level,
name: name
};
Note that I have removed the array literal -- the [] around the object literal. I can't imagine you need it, but you could always put it back in if you genuinely did.
Maybe you should do:
data2[i] = [{
"id": id,
"level": level,
"name": name
}];
var data = {};
$('.content').each(function(i) {
var id = $(this).attr('id'),
level = $(this).attr('level'),
name = $(this).find('textarea').val(),
data2 = {};
data2[i] = [{
"id": id,
"level": level,
"name": name}];
};
$.extend(data, data2);

Categories

Resources