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);
}
Related
The Problem is the following:
I have a JSON file that has objects with the following name: "item0": { ... }, "item1": { ... }, "item2": { ... }. But I can't access them when going through an if method.
What I've done so far:
$.getJSON('/assets/storage/items.json', function(data) {
jsonStringify = JSON.stringify(data);
jsonFile = JSON.parse(jsonStringify);
addItems();
});
var addItems = function() {
/* var declarations */
for (var i = 0; i < Object.keys(jsonFile).length; i++) {
path = 'jsonFile.item' + i;
name = path.name;
console.log(path.name);
console.log(path.type);
}
}
If I console.log path.name it returns undefined. But if I enter jsonFile.item0.name it returns the value. So how can I use the string path so that it's treated like an object, or is there an other way on how to name the json items.
As others stated 'jsonFile.item' + i is not retrieving anything from jsonFile: it is just a string.
Other issues:
It makes no sense to first stringify the data and then parse it again. That is moving back and forth to end up where you already were: data is the object you want to work with
Don't name your data jsonFile. It is an object, not JSON. JSON is text. But because of the above remark, you don't need this variable
Declare your variables with var, let or const, and avoid global variables.
Use the promise-like syntax ($.getJSON( ).then)
Iterate object properties without assuming they are called item0, item1,...
Suggested code:
$.getJSON('/assets/storage/items.json').then(function(data) {
for (const path in data) {
console.log(data[path].name, data[path].type);
}
});
What you want is to use object notation using a dynamic string value as a key instead of an object key. So, instead of using something like object.dynamicName you either have use object[dynamicName].
So in your example it would be like this.
path = 'item' + i;
jsonFile[path].name
I'm afraid you cannot expect a string to behave like an object.
What you can do is this:
path = `item${i}`
name = jsonFile[path].name
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.
I need to pass an array as parameter but i have a problem, i dont know how to explain it so here is the example:
I have this code:
var doc = document;
var Class = {};
Class.Validate = function(opc)
{
alert(opc.id);//
return Class;// when returns the object the alert trigger as expected showing "#name"
};
Class.Validate({
id: "#name",
})
But what im trying to do is this:
var Class = {};
Class.Validate = function(opc)
{
alert(opc.name);//when the object is return show display "carlosmaria"
return Class;//
};
Class.Validar({
name: {field:"carlos",field:"maria"},
})
how can i archived that?
alert(opc.name) should return something like {Object object} because it's an objet. The second point is that your object has twice "field" as property.
If you want to use an array, you should call this way:
Class.Validar({
name: ["carlos", "maria"]
})
Then, you could loop over opc.name to concatenate a full name. Something like this:
Class.Validate = function(opc)
{
var name = "";
for (var i=0, len=opc.name.length; i<len; ++i) {
name += opc.name[i];
}
alert(name);//when the object is return show display "carlosmaria"
return Class;//
};
Consider using actual arrays (via array literals):
Class.Validate({
name: ["carlos", "maria"]
});
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.