Key name in associative array - javascript

I'm trying to add items to an associative array but my key name is not being generated properly. My code is as follows:
var room_name = $('#room_name').val();
var item_name = $('#item_name').val();
var item_description = $('#item_description').val();
roominventory[room_name] = { item_name : item_description };
What is happening is I am getting
{
"Correct room name": {
"item_name": "correct item description"
}
}
Everything works except the item_name. I would like the key name to be the value of item_name but instead I'm just getting the text item_name.
Any ideas what I'm doing wrong?

You can't use variables in the object key with the syntax you're using, as they are taken literally. You need to use bracket notation as you are in the setter of roominventory. Try this:
var room_name = $('#room_name').val();
var item_name = $('#item_name').val();
var item_description = $('#item_description').val();
var obj = {};
obj[item_name] = item_description;
roominventory[room_name] = obj;

As an alternative you can use
roominventory[room_name] = {[item_name] : item_description};

As Rory pointed out, you can't use variables in key. you have to use an object which holds the key and value:
//wrong one
var roominventory = {};
var room_name = "something";
var item_name = "something item";
var item_description = "something description";
roominventory[room_name] = {item_name : item_description};
console.log(roominventory);
//correct way
var roominventory1 = {};
var room_name = "something";
var item_name = "something item";
var item_description = "something description";
var obj = {};
obj[item_name] = item_description;
roominventory1[room_name] = obj;
console.log(roominventory1);
https://jsfiddle.net/u2j42wsv/

var room_name = $('#room_name').val();
var item_name = $('#item_name').val();
var item_description = $('#item_description').val();
roominventory = new Array();
roominventory[room_name] = {};
roominventory[room_name][item_name] = item_description;

Related

Javascript looping through variables

So right now this is my current code and I'm trying to figure out a way to loop through the variables I've already declared (Assuming variables 1-9 already have values). I just wanted to know whether this was possible at all?
var title;
var brief;
var hover;
var whatTitle;
var whatDesc;
var whyTitle;
var whyDesc;
var funTitle;
var funDesc;
var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
var whyTitles = [];
var whyDescs = [];
var funTitles = [];
var funDescs = [];
var obj = {'titles' : title};
if(localStorage.getItem('titles') != null) {
var tmp = JSON.parse(localStorage.getItem('titles'));
for(var i = 0;i<tmp.length;i++) {
titles.push(tmp[i]);
}
}
titles.push(obj);
localStorage.setItem("titles", JSON.stringify(titles));
Output I want if we printed out the looped code:
var obj = {'titles' : title};
if(localStorage.getItem('titles') != null) {
var tmp = JSON.parse(localStorage.getItem('titles'));
for(var i = 0;i<tmp.length;i++) {
titles.push(tmp[i]);
}
}
titles.push(obj);
localStorage.setItem("titles", JSON.stringify(titles));
var obj = {'briefs' : brief};
if(localStorage.getItem('briefs') != null) {
var tmp1 = JSON.parse(localStorage.getItem('briefs'));
for(var i = 0;i<tmp.length;i++) {
briefs.push(tmp[i]);
}
}
briefs.push(obj);
localStorage.setItem("briefs", JSON.stringify(briefs));
var obj = {'hovers' : hover};
if(localStorage.getItem('hovers') != null) {
var tmp2 = JSON.parse(localStorage.getItem('hovers'));
for(var i = 0;i<tmp.length;i++) {
hovers.push(tmp[i]);
}
}
hovers.push(obj);
localStorage.setItem("hovers", JSON.stringify(hovers));
...etc
If the code is running in a browser, then you can do something like:
for(key in window) { console.log(window[key]) } // print all variables
The variables are associated to the global namespace. That is to say the upmost "this" reference or the window object.
You're almost there with the code you have. If you look at your "desired output" examples, you'll see that the only thing that really differs between each element of your "unrolled loop" is the key for local storage ('titles', 'briefs', 'hovers').
With that in mind, you could use an Object to map the keys to the variables you have at the top level. So this:
var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
...
Becomes (UPDATE: with the initializer values preserved):
var key_to_collection = {
'titles': [title],
'briefs': [brief],
'hovers': [hovers],
'whatTitles': [whatTitles],
'whatDescs': [whatDescs],
}
Then, you loop over the values of this object:
Object.keys(key_to_collection).forEach(function(key) {
var obj = {};
collection = key_to_collection[key];
obj[key] = collection;
if(localStorage.getItem(key) != null) {
var tmp = JSON.parse(localStorage.getItem(key));
for(var i = 0;i<tmp.length;i++) {
collection.push(tmp[i]);
}
}
collection.push(obj);
localStorage.setItem(key, JSON.stringify(collection));
});
If your variable name is title for example, then you can access it using window['title']. This means that if you define an array of your global variable names:
const varNames = ['title', 'brief', 'hover', ...]
Then you can do a loop like the following
for(const name of varNames) {
const value = window[name]
// do whatever you want using the variable name and value
}
I hope this solves your issue :)

Ajax response conversion

I have this array that is returned by ajax:
console.log(res);
["07Apr|1", "06Apr|3", "05Apr|12", "04Apr|11", "03Apr|0", "02Apr|0", "01Apr|6", "31Mar|0", "30Mar|7", "29Mar|16", "28Mar|5", "27Mar|5", "26Mar|12", "25Mar|9", "24Mar|4", "23Mar|10", "22Mar|16", "21Mar|2", "20Mar|19", "19Mar|22", "18Mar|10", "17Mar|11", "16Mar|10", "15Mar|19", "14Mar|0", "13Mar|4", "12Mar|14", "11Mar|5", "10Mar|26", "09Mar|7", "08Mar|5"]
I convert this array using JSON.stringify:
(The variable "res" is the response of my ajax -as shown above)
var obj = [];
var daysBack = 30;
var objItem = {};
for(var x = 0; x <= daysBack; x++){
var currObj = res[x];
var objCombo = currObj.split("|");
var objItem = "{date: '"+objCombo[0]+"', downloads: '"+objCombo[1]+"'}";
objItem = JSON.stringify(eval("(" + objItem + ")"));
obj.push(objItem);
}
When I dump the "obj" to the console I get:
console.log(obj);
["{"date":"07Apr","downloads":"1"}", "{"date":"06Apr","downloads":"3"}", "{"date":"05Apr","downloads":"12"}", "{"date":"04Apr","downloads":"11"}", "{"date":"03Apr","downloads":"0"}", "{"date":"02Apr","downloads":"0"}", "{"date":"01Apr","downloads":"6"}", "{"date":"31Mar","downloads":"0"}", "{"date":"30Mar","downloads":"7"}", "{"date":"29Mar","downloads":"16"}", "{"date":"28Mar","downloads":"5"}", "{"date":"27Mar","downloads":"5"}", "{"date":"26Mar","downloads":"12"}", "{"date":"25Mar","downloads":"9"}", "{"date":"24Mar","downloads":"4"}", "{"date":"23Mar","downloads":"10"}", "{"date":"22Mar","downloads":"16"}", "{"date":"21Mar","downloads":"2"}", "{"date":"20Mar","downloads":"19"}", "{"date":"19Mar","downloads":"22"}", "{"date":"18Mar","downloads":"10"}", "{"date":"17Mar","downloads":"11"}", "{"date":"16Mar","downloads":"10"}", "{"date":"15Mar","downloads":"19"}", "{"date":"14Mar","downloads":"0"}", "{"date":"13Mar","downloads":"4"}", "{"date":"12Mar","downloads":"14"}", "{"date":"11Mar","downloads":"5"}", "{"date":"10Mar","downloads":"26"}", "{"date":"09Mar","downloads":"7"}", "{"date":"08Mar","downloads":"5"}"]
Now, I want to change the above array format from this one:
["{"date":"07Apr","downloads":"1"}", "{"date":"06Apr","downloads":"3"}", "{"date":"05Apr","downloads":"12"}", "{"date":"04Apr","downloads":"11"}", ....]
to that one:
[{"date":"07Apr","downloads":"1"}, {"date":"06Apr","downloads":"3"}, {"date":"05Apr","downloads":"12"}, {"date":"04Apr","downloads":"11"}, ....]
I mean to eliminate the double quotes that enclose the objects in curly braces.
Any ideas would be appreciated...
You can parse the data you received from the ajax response to create the array.
var populateArray = function (ajaxResponse) {
var newArray = [];
ajaxResponse.forEach(function (item, index) {
var props = item.split('|');
var obj = {
date: props[0],
downloads: props[1]
};
newArray.push(obj)
});
return newArray;
}
To demonstrate, try
console.log(populateArray(["07Apr|1", "06Apr|3", "05Apr|12", "04Apr|11", "03Apr|0", "02Apr|0", "01Apr|6", "31Mar|0", "30Mar|7", "29Mar|16", "28Mar|5", "27Mar|5", "26Mar|12", "25Mar|9", "24Mar|4", "23Mar|10", "22Mar|16", "21Mar|2", "20Mar|19", "19Mar|22", "18Mar|10", "17Mar|11", "16Mar|10", "15Mar|19", "14Mar|0", "13Mar|4", "12Mar|14", "11Mar|5", "10Mar|26", "09Mar|7", "08Mar|5"]));
Stringify the entire structure when it is ready, not segments.
Don't use eval ever, use JSON.parse() instead.
var obj = [];
var daysBack = 30;
var objItem = {};
for(var x = 0; x <= daysBack; x++){
var currObj = res[x];
var objCombo = currObj.split("|");
var objItem = {date: objCombo[0], downloads: objCombo[1]};
//objItem = JSON.stringify(eval("(" + objItem + ")"));
obj.push(objItem);
}
obj = JSON.stringify(obj);

jQuery assigning value to array giving error Undefined variable

I'm assigning values to array in forloop But it gives an error that array variable is undefine. following is my code.
$(document).ready(function(){
$("#SubmitBtn").live('click',function(){
var cnt = $("#TotalCnt").val();
var data = [];
for(var i=1; i<=cnt; i++)
{
var fname = $('#fname_'+i).val();
var lname = $('#lname_'+i).val();
var address = $('#address_'+i).val();
data[i]["fname"] = fname;
data[i]["lname"] = lname;
data[i]["address"] = address;
}
});
});
when I'm assigning value to array it gives error "data[i] is undefined"
Try to create an empty object first, because initially data[i] is undefined. And undefined does not contains any property under it.
$(document).ready(function(){
$("#SubmitBtn").live('click',function(){
var cnt = $("#TotalCnt").val();
var data = [];
for(var i=1; i<=cnt; i++)
{
var fname = $('#fname_'+i).val();
var lname = $('#lname_'+i).val();
var address = $('#address_'+i).val();
data[i] = {};
data[i]["fname"] = fname;
data[i]["lname"] = lname;
data[i]["address"] = address;
}
});
});

combining multiple arrays into an object with first array items as the key

I have these following arrays
var category = ['Guitar', 'Bass', 'Amps'];
var platform_a = ['platform-a1','platform-a2','platform-a3'];
var platform_b = ['platform-b1','platform-b2','platform-b3'];
var platform_c = ['platform-c1','platform-c2','platform-c3'];
And I want to convert them into a json which should look like this
{
"Guitar":["platform-a1","platform-a2","platform-a3"],
"Bass":["platform-b1","platform-b2","platform-b3"],
"Amp":["platform-c1","platform-c2","platform-c3"]
}
How would I do this? I would have to do this in pure javascript
Let's present three different approaches to your case:
First one
If you want just to create the json object with your data try:
http://jsfiddle.net/csdtesting/tap2xom9/
var platform_a = ['platform-a1', 'platform-a2', 'platform-a3'];
var platform_b = ['platform-b1', 'platform-b2', 'platform-b3'];
var platform_c = ['platform-c1', 'platform-c2', 'platform-c3'];
var category = ['Guitar', 'Bass', 'Amps'];
var obj = {
Guitar: platform_a,
Bass: platform_b,
Amps: platform_c
};
document.write(JSON.stringify(obj));
Second
If you want to create it dynamically do something like that:
http://jsfiddle.net/csdtesting/tap2xom9/
var category = ['Guitar', 'Bass', 'Amps'];
var platform_a = ['platform-a1', 'platform-a2', 'platform-a3'];
var platform_b = ['platform-b1', 'platform-b2', 'platform-b3'];
var platform_c = ['platform-c1', 'platform-c2', 'platform-c3'];
var FinalObject = {};
FinalObject[category[0]] = platform_a;
FinalObject[category[1]] = platform_b;
FinalObject[category[2]] = platform_c;
document.write(JSON.stringify(FinalObject));
Finally
If you want to be more dynamic then try this :
http://jsfiddle.net/csdtesting/kqwz72os/
var FinalObject = {};
var category = ['Guitar', 'Bass', 'Amps'];
var platforms = {
platform_a: ['platform-a1', 'platform-a2', 'platform-a3'],
platform_b: ['platform-b1', 'platform-b2', 'platform-b3'],
platform_c: ['platform-c1', 'platform-c2', 'platform-c3']
};
for (var i = 0; i < category.length; i++) {
FinalObject[category[i]] = platforms[Object.keys(platforms)[i]];
}
document.write(JSON.stringify(FinalObject));
Hope this helps!
There's no reasonable shortcut here. You just have to do it manually:
var jsonString = JSON.stringify({
"Guitar": platform_a,
"Base": platform_b,
"Amp": platform_c
});

JSON.parse using reviver function

How to use JSON.parse reviver method to edit a certain value.
I just want to edit every key which is declared as lastname and than return the new value.
var myObj = new Object();
myObj.firstname = "mike";
myObj.lastname = "smith";
var jsonString = JSON.stringify(myObj);
var jsonObj = JSON.parse(jsonString, dataReviver);
function dataReviver(key, value)
{
if(key == 'lastname')
{
var newLastname = "test";
return newLastname;
}
}
After checking for the special case(s), you simply need to pass back unmodified values by default:
var myObj = new Object();
myObj.firstname = "mike";
myObj.lastname = "smith";
var jsonString = JSON.stringify(myObj);
var jsonObj = JSON.parse(jsonString, dataReviver);
function dataReviver(key, value)
{
if(key == 'lastname')
{
var newLastname = "test";
return newLastname;
}
return value; // < here is where un-modified key/value pass though
}
JSON.stringify(jsonObj )// "{"firstname":"mike","lastname":"test"}"

Categories