I'm sure this is a simple question, but I can't find any information to help me, and I've been lost for a while. I'm trying to create a JSON object, and here is what I have so far:
var myJsonObject = new Object();
myJsonObject.context.applicationName = appName;
myJsonObject.context.ID = ID;
myJsonObject.context.domain = domain;
myJsonObject.context.production = "no";
myJsonObject.other.name = userName;
myJsonObject.other.date = userDate;
var myString = JSON.stringify(myJsonObject);
and here is what I want my JSON string to look like.
{
"context": {
"applicationName":"example",
"ID":"exampleID",
"domain":"someDomain",
"production","no"
},
"other": {
"name":"userName1",
"date":"userDate1"
}
}
However, I keep getting myJsonObject.context is undefined errors. I mean, I understand why it's happening, I never actually initialize it, but I don't know how to go about correcting this. Any help would be appreciated.
I'm guessing the myJsonObject.context has to be initialized as another object, and then I just add it to my original object as an array of objects....is this correct?
Yes, you need to first set it to an object, or you can just set them on the first line:
var myJsonObject = {context : {} , other: {} };
Also note that you can define your objects using a shorter syntax, like so:
var myJsonObject = {
context: {
applicationName: appName,
ID: ID,
domain: domain,
production: "no"
},
other: {
name: userName,
date: userDate
}
};
I'm guessing the myJsonObject.context has to be initialized as another object
Yes
and then I just add it to my original object
You'd generally do that at the same time
as an array of objects
No. You have nothing resembling an array there.
var myJsonObject = {};
myJsonObject.context = {};
myJsonObject.context.applicationName = appName;
Define myJsonObject.context = {}; property first.
Related
I have an array of countries, where each country have three properties.
const countries = [
{ name: "Poland", alpha: "POL", code: "616" },
{ name: "Hungary", alpha: "HUN", code: "348" },
// and so on...
]
Later on I want to easily access each country by any of these properties.
I was thinking of reducing this array to an object that would have three keys for each country pointing to the very same country object.
Something like this:
const countriesObject = countries.reduce((object, country) => {
const { name, alpha, code } = country;
// Create individual country object
object[name] = { ...country };
// Reference just created country object
object[code] = object[name];
object[alpha] = object[name];
return object;
});
In the end I could access each country object either by its name, code or alpha.
countriesObject["Poland"] // →
countriesObject["POL"] // → The same object
countriesObject["616"] // →
My question is, would it be considered good practice, or there are some better ways to achieve the same or similar result?
Thank you!
That's fine, as all of those keys, as you correctly noted, will be pointing to the same object. The biggest problem that I see here is that it's easy to reduce readability of the code by using this approach. Let's say we have this fragment:
console.log( countriesObject[id] );
The question is, what is id here? Is it full country name? or just alpha? or code? You might just not care, true, but if you do, consider giving them additional structure:
const countriesObject = countries.reduce((object, country) => {
const { name, alpha, code } = country;
const countryCopy = { ...country };
// it makes sense to place them on the same line to show the intent
object.name[name] = object.code[code] = object.alpha[alpha] = countryCopy;
return object;
}, { name: {}, code: {}, alpha: {} });
Another potential issue is that you won't be able to drop the countries easily from this object; it's not enough to delete just a single key pointing to it, you'll have to go and remove all three. But that doesn't seem to be a big thing here; this looks more like a dictionary.
You can indeed write it like this:
var countries = {[
"poland": {
alpha: "POL", code: "616"
},
"hungary": {
alpha: "HUN", code: "348"
}
]}
Accessing each country like this:
var poland = countries.poland;
This, in turn, produces more readable code:
var alpha = countries.poland.alpha;
instead of
var alpha = countries[0].alpha;
But there is no set preference.
Docs
I was trying to access sub-properties from a javascript file and it's giving me something weird!
Suppose this is my JS file named data.js
module.exports = {
something: {
name: "Something",
num: 1,
email: "something#gmail.com"
},
somethingtwo: {
name: "Something Something",
num: 2,
email: "somethingtwo#gmail.com"
},
};
In my main js file named app.js, where I need to access it, it looks like
var persons = require('./data.js');
var getAName = function() {
for(var name in persons) {
console.log(name.email);
}
}
I really don't know what goes wrong but I have been trying this for quite a long time now. The expected output is the email Ids from the data.js file but instead, i get undefined times the number of entries (if there are 2 entries in data.js, then I get 2 undefine and so on).
How can I access the email or the num from the data.js without those undefines?
console.log(name) is returning something somethingtwo
Well, name.email is undefined because name is a string.
You can test that by writing
console.log(typeof name);
Now, to solve your problem, you need to access the property correctly:
var getAName = function() {
for (var name in persons) {
console.log(persons[name].email)
}
}
Returns:
something#gmail.com
somethingtwo#gmail.com
for(var name in persons) {
//persons is actually an object not array
//you are actually iterating through keys of an object
//var name represent a key in that object
console.log(persons[name]); //value corresponding to the key
}
I guess this code will give you the desired result.
You should be using console.log(persons[name].email)
require don't automatically calls the module
var DataArchive = require('./data.js');
var module = DataArchive.module;
var persons = module.exports;
var getAName = function() {
for(var person in persons) {
//person should be something (first iteration) and somethingtwo (second iteration)
console.log(person.email);
}
I have the following code:
d3.csv("flights-airport_3.csv", function(flights) {
var linksByOrigin = {},
countByAirport = {},
cancelledByAirport = {},
locationByAirport = {},
positions = [];
var arc = d3.geo.greatArc()
.source(function(d) { return locationByAirport[d.source]; })
.target(function(d) { return locationByAirport[d.target]; });
flights.forEach(function(flight) {
var origin = flight.origin,
destination = flight.destination,
count_airport = flight.count,
cancelledByAirport = flight.count_cancelled,
links = linksByOrigin[origin] || (linksByOrigin[origin] = []);
links.push({source: origin, target: destination});
My flights data array looks like this:
0: Object
"": ""
count: "9"
count_cancelled: "0"
destination: "IAD"
origin: "ALB"
For some reason my cancelledByAirport is empty? I am not sure why since I am treating it exactly the same as my countByAirport variable. Can anyone help?
I think your problem is that you have two variables called "cancelledByAirport". One is declared just below d3.csv(...), another within foreach().
The solution would be giving different names to those variables, or perhaps getting rid of one of them.
Please review your code with respect to those two variables, and tell us what you find.
I would like to be able to reference an array by using a string, as such:
var arrayName = "people";
var people = [
'image47.jpeg',
'image48.jpeg',
'image49.jpeg',
'image50.jpeg',
'image52.jpeg',
'image53.jpeg',
'image54.jpeg',
'image55.jpeg',
]
function myFunc (arrayName)
{
//arrayName is actually just a string that evaluates to "people", which then in turn would reference the var people, which is passed in.
}
Any thoughts on how to do this? Sorry if I'm missing something obvious.
You can simply create a global dictionary, like this:
var people = ['image47.jpeg', 'image48.jpeg'];
var cars = ['image3.png', 'image42.gif'];
var global_arrays = {
people: people,
cars: cars
};
function myFunc(arrayName) {
var ar = global_arrays[arrayName];
// Do something with ar
}
Note that the first line of myFunc makes it clear that this is just a complicated way of having myFunc accept the array itself in the first place. I strongly suggest that you do just that, like this:
function myFunc(ar) {
// Do something with ar
}
myFunc(people);
This means that your code will be reusable by anyone else (say, a third-party plugin that wants to render giraffes) and not require any global variables.
If your array is declared outside of a function, you can access it using the this keyword like so:
function myFunc(arrayname) {
var itemzero = this[arrayname][0];
}
var arrayName = "people";
var people = [
'image47.jpeg',
'image48.jpeg',
'image49.jpeg',
'image50.jpeg',
'image52.jpeg',
'image53.jpeg',
'image54.jpeg',
'image55.jpeg',
]
function myFunc (arrayName)
{
//Here you can use this or window obj To quote you array.
//such as window[arrayName]
}
I want to create an object like this:
var servers =
{
'local1' :
{
name: 'local1',
ip: '10.10.10.1'
},
'local2' :
{
name: 'local2',
ip: '10.10.10.2'
}
}
This is what I'm doing
$.each( servers, function( key, server )
{
servers[server.name] = server;
});
Where servers is an array of objects like these:
{
name: 'local1',
ip: '10.10.10.1'
}
But the code above does not assign any keys to the object, so the keys default to 0,1,2....
One potential bug I notice is that you're modifying the object that you are iterating over (servers). It might be good to create a new empty object that you modify in the loop.
Also, it'd help if you posted some sample data so we can run your code for ourselves.
Finally, you could try inserting a debugger keyword in there and stepping through the code.
In Chrome if You run this:
a = [];
b = {n:"c",i:"1.2.3.4"};
a[b.n] = b;
alert (a["c"].i);
alert (a.c.i);
You will got the "1.2.3.4" string as expected. But if you change the example as:
a = {};
b = {n:"c",i:"1.2.3.4"};
a[b.n] = b;
alert (a.c.i);
You will get the same "1.2.3.4" again :). So the answer is: your code assigns the properties to the objects as you asked. The only difference is that in the first example you used the array as object, and in second the simple object.
AFAIK [] in javascript is used to index arrays, while to access object properties you have to use dot notation. So your code should be:
$.each( servers, function( key, server )
{
var name = server.name;
eval("servers." + name + " = server");
});
Please try it out since I don't test it.