I want to access a Javascript Object dynamicly.
Example:
example: {
name: "dev.pus",
year: 2012,
os: "linux"
}
This isn't anything new. Now you normaly can access properties of the "example" with:
console.log(example.name);
// or
console.log(example.year);
But what is if I want to take the attribute dynamicly?
For example, another var (lets assume the user sets it) should decide which property we want:
var = "name";
console.log(example.var); // error
console.log(example[var]); // error
What is the way to go?
Your example should work if you'll change your variable name (var is reserved).
var key = 'name';
console.log(example[key]);
You can also iterate over your object to get all keys:
for (var item in example){
if (example.hasOwnProperty(item)){
console.log(example[item]);
}
}
http://jsfiddle.net/bC9XJ/
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 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);
}
Following on from this question, I would like to create a DRY way of creating Js variables for a D3 graph which represents daily sentiment analysis of UK newspapers.
Here is some example code from my script:
var guardian,independent; // many more here
var gLine,gChart; // many more here
var iLine,iChart; // many more here
I am storing the newspaper-specific variables in an object:
var allObjects = { guardian : {line : gLine,chart : gChart},
independent : {line : iLine,chart : iChart}}// and so on for each newspaper
I assign the variables using functions as follows:
function makeLine(name){return d3.svg.line().y(function(d) { return y(d[name]); }); }
// and so on for each newspaper attribute in AllObjects
Rather than repeating myself all the time, making each object individually:
makeLine('guardian'); makeLine('independent'); // etc
...which works fine, I would like to be able to iterate over all the newspapers, and assign the objects with a single function for all newspapers, something like:
var allFunctions = {line: makeLine(),chart: makeChart()};
function make(type){
var myFunc = allFunctions.type;
for(var prop in allObjects){prop.type = myFunc(type);}
}
So that make(line) would assign gLine, iLine, etc
The problem is that as the variables in allObjects.guardian are undefined, this method isn't working.
Any suggestions as how to refactor in this way?
Rather than repeating myself all the time, making each object individually:
makeLine('guardian'); makeLine('independent'); // etc
...which works fine, I would like to be able to iterate over all the newspapers, and assign the objects with a single function for all newspapers
If I'm reading that right, your "something like" is really close, see comments:
var allFunctions = {line: makeLine, chart: makeChart};
// Note no () here ----------------^ or here --------^
// We want the reference to the function, we don't want to call it (yet)
// Assuming `type` is "line", "chart", etc.
function make(type){
// Note brackets: We want the property whose name is in the type
// variable, not a property actually called "type"
var myFunc = allFunctions[type];
// ^----^------ We want the property whose name is in
// the `type` variable, not a property
// actually *called* "type"
for (var prop in allObjects) {
allObjects[prop][type] = myFunc(prop);
// ^----^-----^----------- Brackets again as above
}
}
Object :
var userData = {
"a1":{"a":"1"},
"b2":{"b":"2"},
"c3":{"c":"3"},
"d4":{"d":"4"},
"e5":{"e":"5"},
};
I need to delete Object with key "a1" and place a new object i.e. "f6" at same place.
i.e.
userData["f6"] = userData["a1"];
userData["f6"].new = "true";
delete userData["a1"];
Output:
userData = {
"b2":{"b":"2"},
"c3":{"c":"3"},
"d4":{"d":"4"},
"e5":{"e":"5"},
"f6":{"a":"1", new:true},
};
Expected O/p:
var userData = {
"f6":{"a":"1", new:true},
"b2":{"b":"2"},
"c3":{"c":"3"},
"d4":{"d":"4"},
"e5":{"e":"5"},
};
Thanks in Advance..
In Javascript, objects have no specific order for their properties. When you see them as a JSON, the properties are shown in the same order they where declared or added. To mantain a specific order, you may do changes in your object and implement an Array.
I have an associative array here -
var dataset = {
"person" : [
{"userLabels": ["Name","Role"]},
{"tagNames": ["lName","role"]},
{"tableClass": "width530"},
{"colWidths": ["50%","50%"]}
]
}
I tried accessing the 'userLabels' object using jQuery using various methods but I failed. I think I am doing something wrong with basics. I want the userLabels object to be accessed using jQuery and the result should be an array, so I can perform the jQuery.inArray() operation.
Firstly, here's how you can access dataset using the method you have.
var dataset =
{
"person" : [
{"userLabels": ["Name","Role"]},
{"tagNames": ["lName","role"]},
{"tableClass": "width530"},
{"colWidths": ["50%","50%"]}
]
};
alert(dataset['person'][0]['userLabels']); //style 1
alert(dataset.person[0]['userLabels']); //style 2
alert(dataset.person[0].userLabels); //style 3
//Also you can use variables in place of specifying the names as well i.e.
var propName ='userLabels';
alert(dataset.person[0][propName]);
//What follows is how to search if a value is in the array 'userLabels'
$.inArray('Name', dataset.person[0].userLabels);
I'd like to ask why you're doing this in a such an 'interesting way'. Why don't you just make them all objects?
That's what I would do if I were you because if you think about it, a person IS an object and it should be noted that arrays are basically objects in Javascript with a 'length' property, though I won't elaborate on it here (feel free to do some research though). I'm guessing it's because you don't know how to iterate over object properties. Of course if it makes more sense to you, go for it.
Note one of the differences between an array and an object is that object properties need to be defined; you'll notice that I gave 'Name' and 'Role' values of 'undefined' below.
In any case, here is what I would do:
var dataset =
{
"person" : {
"userLabels": {"Name" : undefined,"Role": undefined},
"tagNames": {"lName" : undefined,"role" : undefined},
"tableClass": "width530",
"colWidths": ["50%","50%"]
}
};
for (var i in dataset) { //iterate over all the objects in dataset
console.log(dataset[i]); //I prefer to use console.log() to write but it's only in firefox
alert(dataset[i]); // works in IE.
}
//By using an object all you need to do is:
dataset.person.userLabels.hasOwnProperty('Role'); //returns true or false
Anyways, hope this helps.
var basic = dataset.person[0].userLabels;
// | | |
// | | --- first element = target object
// | --- person property
// ---- main-object
var userLabels = dataset.person[0].userLabels;
if ($.inArray(yourVal, userLabels) !== -1) {
doStuff();
}