Associative style arrays in Javascript? - javascript

I'm trying to assign an object in the style of an associate array in JS but it's failing, saying 'task.id' is undefined. Why is this?
var response = Object();
$('.task-list').each(function() {
response[this.id][$('#' + this.id).sortable('toArray')];
});

You are referencing the object as a two dimensional array.
You should do it more like this:
var response = {};
$(".task-list").each(function () {
response[this.id] = $(this).sortable('toArray');
}
Also, when you say the error is "task.id is undefined", do you mean "this.id is undefined"? If you are selecting elements based on class, they may not have an explicit id.
<span class="task-list">myTask</span>
You may want to include an id:
<span class="task-list" id="myTask">myTask</span>

You are trying to access a property that you haven't created yet. Although it's not actually clear what you are trying to do from your example. I'm assuming you want to set the value of response[this.id] to $('#' + this.id).sortable('toArray')?
Try this instead:
var response = {};
$('.task-list').each(function() {
response[this.id] = $(this).sortable('toArray');
});
Also changed it to use $(this) instead of $('#' + this.id) as it's cleaner imo.

Related

How to retrieve a specific object from a JSON value stored in sessionStorage?

I have this stored in the session:
What I'm looking to do is assign each object in the JSON as a variable so I can add them to the DOM appropriately.
This works but prints everything out:
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
$(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9')).appendTo('.div');
}
What I'd like is something like this, but it doesn't work:
var div1 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.cart-contents')));
var div2 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.footer-cart-contents')));
var div3 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'div.widget_shopping_cart_content')));
Any help would be greatly appreciated. Thank you!
Getting the same value from the storage several times is not a good idea. In addition, you need better names for your variables.
var json = sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
if (json) {
var data = JSON.parse(json);
if (data) {
var cart_link = $(data['a.cart-contents']),
footer_link = $(data['a.footer-cart-contents']),
widget_div = $(data['div.widget_shopping_cart_content']);
}
}
So it appears you have set selectors as keys of the object so you could iterate those keys to get each selector.
The propose of those selector keys is not 100% clear. I am assuming that those selectors are the elements you want to insert the html strings into and that $() means you are using jQuery
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
var data = JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
$.each(data, function(selector, htmlString){
$(selector).append(htmlString)
});
}

Assign value of variable from JS array based on key

I have a variable that takes its value from the current object's ID attribute, it will always look something like filtercolor-red:
$('.facet-options-list li input[id*=filtercolor]').each(function() {
var filterColor = $(this).attr('id');
...
});
I also have an array that lists possible ID's and a corresponding HEX code:
var activeFilterBg;
var filterBgColor = [];
filterBgColor = {
filtercolor-black: '#171710',
filtercolor-blue: '#4C94B6',
filtercolor-brown: '#50443D',
filtercolor-gold: '#F6D069',
filtercolor-green: '#96B14D',
filtercolor-grey: '#A8AAA5',
filtercolor-orange: '#DB5E46',
filtercolor-pink: '#E78EB1',
filtercolor-purple: '#59547E',
filtercolor-red: '#D22200',
filtercolor-silver: '#EBEBEB',
filtercolor-white: '#FFF'
};
What I'd like to do is take filterColor and assign activeFilterBg the appropriate HEX code from filterBgColor. I could do this with a switch, but that seems kind of sloppy and gives a lot of room for mistakes in the future.
Do I have an option to somehow lookup the correct key and then assign a variable based upon it?
That's not an array, that's an object. You assign an array to the variable, but then you immediately replace that with an object. An object works well for this, so just skip that array. (Note though, as Jordan pointed out, that the parameter names has to be quoted when they contain dashes.)
You can use the bracket syntax to access the object properties using the variable:
var activeFilterBg;
var filterBgColor = {
'filtercolor-black': '#171710',
'filtercolor-blue': '#4C94B6',
'filtercolor-brown': '#50443D',
'filtercolor-gold': '#F6D069',
'filtercolor-green': '#96B14D',
'filtercolor-grey': '#A8AAA5',
'filtercolor-orange': '#DB5E46',
'filtercolor-pink': '#E78EB1',
'filtercolor-purple': '#59547E',
'filtercolor-red': '#D22200',
'filtercolor-silver': '#EBEBEB',
'filtercolor-white': '#FFF'
};
$('.facet-options-list li input[id*=filtercolor]').each(function() {
var filterColor = $(this).attr('id');
activeFilterBg = filterBgColor[filterColor];
});
Check the object first with hasOwnProperty - and if the property exists, use it!
$('.facet-options-list li input[id*=filtercolor]').each(function() {
var filterColor = this.id; //$(this).attr('id');
var color;
if (filterBgColor.hasOwnProperty(filterColor) {
color = filterBgColor[filterColor];
} else {
color = "#FFF"; //not found
}
});
mapping the id to the color should be as simple as
var filterColor = $(this).attr('id');
var hexCode = filterBgColor[filterColor];
//then do whatever with the hexCode

Trouble with getting access to an object's property

I'm having a trouble with getting access to an object's property.
Isn't it possible to get access to an object's property like this?
key["heading"]
key in the code above is a variable.
This code below is the code I'm working on right now.
alertHeading.on('blur', function(){
var inputtedVal = $(this).val();
var key = alertMode.val();
chrome.runtime.getBackgroundPage(function(backgroundPage) {
var background = backgroundPage.background;
//(1)This works fine.
background.setStorage(key, {heading:inputtedVal});
console.log(background.getStorage(key));// Object {heading: "aaa"}
//(2)This doesn't work.
var alertObject = background.getStorage(key["heading"]);
console.log(alertObject);// null. I'm expecting to get "aaa".
});
})
I think I'm making a very simple mistake which comes from my lack of javascript knowledge.
Please help me out to solve this problem.
Your key isn't an object, it's a string. It is the return from background.getStorage(key) that is an object, so you can do this:
var alertObject = background.getStorage(key)["heading"]; // note () and [] placement
// OR, in two steps:
var alertObject = background.getStorage(key);
var heading = alertObject["heading"];
EDIT:
"I haven't understood why it's not an object but a string yet"
Your key variable is set to the return from jQuery's .val() method:
var key = alertMode.val();
...which returns a string that is the value of the form element that it is called on. Add in a console.log(key) and you'll see.

jQuery getting value from dynamic array

I have an array with divs ids (in my case its all divs ID values od parent div (#area) ):
jQuery.fn.getIdArray = function () {
var ret = [];
$('[id]', this).each(function () {
ret.push(this.id);
});
return ret;
};
var array = $("#area").getIdArray();
I need to get an array field value, something like this:
var lef = $("#array".[0]).css("left");
Taking a wild swing at it (see my comment on the question):
var array = $("#area").getIdArray();
var lef=$("#" + array[0]).css("left");
That assumes that getIdArray returns an array of strings, where each string is an id value for a DOM element, and that you want to get the left value for the first of those elements.
So for instance, if the array comes back as:
["foo", "bar", "charlie"]
then the selector created by "#" + array[0] is #foo, so you end up getting the left value for the foo element.
If you have an actual JS array within your variable array just use bracket notation to access each individual ID.
// I have the # before-hand since I'm assuming you have just the ID name
var lef = $('#' + array[0]) // this will access the 1st one in the array
I think you are looking for this :
var divYouWantToChange = $("#"+array[0]);
I try to formulate this as an answer because getIdArray is not a jquery function and we don't know what it does. If you'd like to apply a custom filter to the $("#area") collection you can do so using filter. This will return a jquery object where you can get the .css("left") from.
If you'd like to save both the id's and the left property you can do so with the following code:
var objects=[];
$("#area").filter(function(){
$this=$(this);//cache the object
objects.push({id:$this.attr("id"),
left:$this.css("left")
};
});
console.log(objects);

Uncaught TypeError: Object #<HTMLDivElement> has no method 'attr'

Im trying to grab my divs with the class tooltip.
And then do something like this:
var schemes = $(".tooltip");
for (var i in schemes) {
var scheme = schemes[i];
console.log(scheme.attr("cost"));
}
But it throws the above error. What am i missing? (Im new to javascript + jquery obviously)
If you use for-loop to iterate jQuery set, you should get the elements with eq() method, but not using square bracket notation (i.e. []). The code like $(".tooltip")[i] will pick up DOM elements, but not jQuery objects.
var schemes = $(".tooltip");
for (var i = 0; i < schemes.length; i++) {
var scheme = schemes.eq(i);
console.log(scheme.attr("cost"));
}
However, you may always use each() to iterate jQuery set:
$(".tooltip").each(function() {
var scheme = $(this);
console.log(scheme.attr("cost"));
});
var schemes = $(".tooltip");
schemes.each(function(index, elem) {
console.log($(elem).attr('cost'));
});
As a sidenote "cost" is not a valid attribute for any element as far as I know, and you should probably be using data attributes.

Categories

Resources