Dynamic name in json key - javascript

I'm trying to make a JSON dynamically but when I do something like this:
var jsonVar = {
"section": {}
}
var elementsStoragePrefix = "_app_",
elementName = elementsStoragePrefix + "some_name";
$.extend(jsonVar .section, { elementName: "<option>This is a text</option>"});
I got the key as elementName and not _app_some_name
jsonVar.section =>
Object
elementName: "<option>This is a text</option>"
__proto__: Object

When creating object literals, you don't need to quote the property names, so in your example elementName will be taken literally. Thankfully, you can use the square-bracket-syntax (or however you spell that):
var extendObject = {};
extendObject[elementName] = '<option>Foobar</option>';
$.extend(jsonVal.section, extendObject);
//or, to use brackets all the way:
$.extend(jsonVal['section'], extendObject);
That should fix things for you

jsonVar.section[elementName] = "<option>This is a text</option>";

Related

JavaScript selecting Object Arraylike?

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

How would I go about using a multidimensional array variable in javascript

Hi there before I start I did try looking through the search about writing variables so if this has been asked and answered then I do apologise but this is baffling me ....
So here goes ..
example of what I am talking about
var i = e[ab]
var n = e[cd][ef]
var t = e[cd][gh]
I know that when I want var i I can put e.ab but how would I go about writing var n and var t
So assuming your object looks like this (based on your description, it sounds like you want to access an object which is the property of another object), and you want to access them through the indexer properties (which would be a property of a property).
var e = {
ab : "variableOne",
cd : {ef:"ef object"},
gh : {ij:"ij object"},
}
var i = e["ab"]
//if these are properties, then you need to add quotes around them
//to access a property through the indexer, you need a string.
var n = e["cd"]["ef"]
var t = e["gh"]["ij"]
console.log(i);
console.log(n);
console.log(t);
console.log("this does the same thing:")
console.log(e.ab);
console.log(e.cd.ef);
console.log(e.gh.if);
In your example the object would look like
//e is the parameter, but I show it as a variable to show
// it's relation to the object in this example.
e = {
now_playing: {artist:"Bob Seger"; track:"Turn the Page"}}
}
this is different than an array of arrays:
var arr = [
['foo','charlie'],
['yip', 'steve'],
['what', 'bob', 'jane'],
];
console.log(arr[0][0]); //foo
console.log(arr[0][1]); //charlie
console.log(arr[1][0]); //yip
console.log(arr[1][1]); //steve
console.log(arr[2][2]); //jane
https://jsfiddle.net/joo9wfxt/2/
EDIT:
Based on the JSON provided, it looks like parameter e in the function is assigned the value of the item in the array. With your code:
this line will display: "Rock you like a hurricane - Nontas Tzivenis"
$(".song_title .current_show span").html(e.title);
and this line will display: "Rascal Flatts - Life is a Highway".
$(".song_title .current_song span").html(e.np);
If it's not displaying you might want to double check your JQuery selectors. This ".song_title .current_song span" is selecting it by the classes on the element.
I think you are in need of a bit of a refresher on basic JavaScript syntax. Here's how you can assign an "empty object" to a variable, then start to assign values to it's properties:
e = {}
e.ab = {}
e.cd = {}
e.cd.ef = "data"
or you can use the associative array syntax for property access:
e = {}
e["ab"] = {}
e["cd"] = {}
e["cd"]["ef"] = "data"
You see the latter is using the object e like a two-deep associative array. Is that what you are looking to do?
JavaScript is not strongly typed. So an Array "a" could contain objects of different types inside.
var a = [ "a value", [1, 2, 3], function(){ return 5 + 2;}];
var result = a[0]; //get the first item in my array: "a value"
var resultOfIndexedProperty = a[1][0]; //Get the first item of the second item: 1
var resultOfFunc = a[2](); //store the result of the function that is the third item of my array: 7
Hope this helps a little.

Add Jquery object as key to another object

Can I add Jquery Object to the blank object as key. For example:-
var obj = {};//blank object
var myId = $("#myId");//jQuery Object
var myId2 = $("#myId2");//another jQuery Object
obj[myId] = "Trying to add myId as a key";
obj[myId2] = "Trying to add myId2 as a key";
But the output of the obj contains only one key. Is the above thing is possible in JS or not?
Thanks in advance.
You have to use a string as property name (e.g. the id of the jquery object?).
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
If you want to keep the reference to object you can use an array of objects instead of an object:
[
{
"jQueryElement": myId1,
"note": "Trying to add myId as a key"
},
{
"jQueryElement": myId2,
"note": "Trying to add myId2 as a key"
}
]
Then you will be able to do:
function getNoteOfJqueryObj(element) {
element = $(element);
for (var i in array) {
if (array[i].jQueryElement[0] == element[0]) {
return array[i].note;
}
}
return undefined;
}
I guess that this is one of the best ways you can choose.
JSFIDDLE

any danger in using an html object as attribute "name" in javascript object?

in linking javascript objects with html objects
// javascript element
var element = { tag:'input', name: 'email', value:null, dom: null,
verifyFunc: function() {...}, postFunc: function() {...},
rcdElement: some_element }
// lookup javascript element from dom
var doms = {};
// create html element for dom
var item = document.createElement(element.tag);
item.name = element.name;
...
// cross-link
doms[item] = element;
element.dom = item;
// using it in generic "onchange" trigger
function changeTrigger(e) {
var el = doms[e.target];
....
};
are there any dangers lurking in this approach?
Object keys are strings. So, when you try to use a DOM object as an object key, it will call toString() on the DOM object and use that as the key. toString() on DOM objects returns non-unique things like this:
[object HTMLParagraphElement]
So, it won't cause an error, but it probably won't do what you want. It would probably make more sense to use the object's ID as the key and generate a unique ID to put on the object if the object doesn't already have an id.
As best I can tell, any use of using an object as a key can also be done with the id as a key.
When I run this in Firefox 10:
window.onload = function(){
var doms = {},
item,
element = {
tag: 'input',
name: 'email',
value: null,
dom: null
};
for (var i = 0; i < 10; i++) {
item = document.createElement(element.tag);
item.name = element.name + i;
document.body.appendChild(item);
doms[item] = element;
}
console.log(doms);
};
I see the following in Firebug's console:
Object { [object HTMLInputElement]={...}}
Which expands to:
[object HTMLInputElement] Object { tag="input", name="email", value=null, more...}
dom null
name "email"
tag "input"
value null
http://jsbin.com/efuluk/
Note, there's only one reference/object pair, not ten. I suspect you can't do this, and I would advise against it anyways (in lieu of a specific citation supporting my hunch).

Is it possible to append value in an existing object - jquery

Consider i am having an object "req".
When i use console.log(req) i get
Object { term="s"}
My requirement is to append an value with the existing object.
My expected requirement is to be like this:
Object { term="s", st_id = "512"}
Is it possible to do the above?
If yes, how ?
Thanks in advance..
There are several ways to do it;
Plain javascript:
var req = { "term" : "s" };
req.st_id = "512";
Because javascript objects behaves like associative arrays* you can also use this:
var req = { "term" : "s" };
req["st_id"] = "512";
jQuery way $.extend():
var req = { "term" : "s" };
$.extend(req, { "st_id" : "512" });
You can do this in a couple of ways:
req.st_id = "512";
or
req["st_id"] = "512";
The second of these is especially useful if the variable name is dynamic, e.g. a variable could be used instead of the string literal:
var key = "st_id";
req[key] = "512";
Yes this is possible, to add properties to a value simply use the following syntax:
req.st_id = "512";

Categories