Simple JSON array - javascript

I want to create a simple array like item_structure = {thumb, head, cont} and here is my code:
$('.items_options').find('#'+item_id+' .option .blog_item_structure li')
.each(function(event) {
var item_class = $(this).attr('class');
item_structure[] = item_class;
});
But it seems that expresion item_structure[] = ... is not working. So does anyone of you know what is rigt syntax?
Thx for your time.

You probably mean to push a value:
item_structure.push(item_class);
This adds item_class as the last element of item_structure.
For this to work item_structure must be an array, most easily made so this way:
item_structure = [];

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)
});
}

Add an Array of Arrays as an Array under a property to an Array

I want to get an output like this:
["userDefined": [["1","2","3"],["4","5","6"],["7","8","9"]],
"anotherDefined":[["a","b","c"],["d","e","f"],["g","h","i"]]]
And this is the code I'm using right now:
var outterArray = [];
var ultimateArray = [];
//This one works
$(document).on("click", '[id^="addArray"]', function () {
var innerArray = [];
innerArray.push(val1, val2, val3);
outterArray.push(innerArray);
});
//This one doesn't
$(document).on("click", '[id^="grouUnderProperty"]', function () {
ultimateArray.push(varByUser:outterArray);
});
Excuse my broken english and thanks in advance.
Edit 2:
Epascarrelo said that I was looking for an object instead of an array, and I think that he might be right, but it still doesn't work under an object, I've tried:
var ultimateArray = {};
ultimateArray.property.push(outterArray);
ultimateArray.property = outterArray;
And it still doesn't work.
Edit 3: I got the answer using a suggestion by Epascarrelo.
This is what is working for me right now:
var definedByUser = "textDefinedByUser";
ultimateArray[definedByUser] = outterArray;
Is giving me:
Object {textDefinedByUser: Array[3]}
Thanks for the help and time, and I'll keep the suggestions in mind if I even need to ask abother question.

$.grep filter with contains

I am trying to filter an array with grep to apply CSS. My code is like below.
var depos = $('.panel-default > .panel-heading');
var chkd = ['ABC','XYZ'];
var found_p = $.grep(depos, function(v) {
return jQuery.inArray(v.innerText,chkd);
});
The first issue is that found_p is not filtering the needed array values from chkd. After filtering it, how can I apply CSS? I tried like below but it fails
$(found_p[0]).css('background-color', 'red');
Can anybody help me out with this.
Assuming from your code that you're trying to find the elements that have innerText matching a value in the chkd array, you can use the filter() method. Try this:
var $depos = $('.panel-default > .panel-heading');
var chkd = ['ABC','XYZ'];
var $found_p = $depos.filter(function() {
return $.inArray($(this).text(), chkd) != -1;
});
The $found_p variable will then hold a jQuery object with all matched elements. You can apply CSS to them like this:
$found_p.css('background-color', 'red');
Example fiddle
However, I would suggest using CSS classes instead of adding inline styles as it is much better practice.

Get only word part of an id/name

I have a div element with lots of descendent's elements, all with ids in the form "word1", for a simple example: id="moviment1" or id="type1".
I need to get only the written part of these ids (moviment or type), in order to concatenate their names with a increment of 1 (id="moviment2" or id="type2").
$clone.find('*').each(function() {
var id = $(this).prop('id');
var num = parseInt( $(this).prop("id").match(/\d+/g), 10 ) +1;
$(this).prop('id', id+num);
});
The way it is, I always get ids like id="moviment12". I already tried:
var id = $(this).prop('id').replace(/\d+/g, '');
or
var id = $(this).prop('id').match(/\w+/);
But I always get errors like "cannot read property 'replace'/'match' of undefined". So, what am I doing wrong? Any other ideas? Thank you very much!
Ideally you should use a template. Traversing and modifying parsed elements makes your code slow and hard to maintain.
If you want to increment the number part of the IDs by 1 you can use the replace method callback function:
$clone.find('[id]').prop('id', function(_, id) {
// Assuming `id` is `test_25_segment`
return id.replace(/(\d+)/, function(num) {
// |
// --- is 25
return +num + 1;
// |
// --- parses the matching string into integer
});
});
Here is a demo using the above snippet.
Easiest way, you could just add those values as data-attr:
<div id="type1" data-id="1" data-text="type"></div>
So you can easily get them separated just using .data('id') and .data('text').
You may select the elements by this way:
var all = [].filter.call(document.querySelectorAll('[id*=type]'), function(el) {
return (/\btype\d+\b/).test(el.id);
});
and then you can change the ids using methods like replace()
Try this...
var onlyAlphabets = id.split(/(\d)/)[0];

How to optimize or make this dynamic (html javascript)

i'm still new in html javascript. I want to ask can i use for loop to optimize or make this dynamic
var port = [];
port[0]=$('#slcPort_0').val();
port[1]=$('#slcPort_1').val();
port[2]=$('#slcPort_2').val();
port[3]=$('#slcPort_3').val();
port[4]=$('#slcPort_4').val();
i used this code in function to retrieve data from html form
thanks
You could use:
// selects all the elements whose 'id' starts-with "slcPort_":
var port = $('[id^=slcPort_]').map(function(){
// returns the value from those elements:
return this.value;
// converts to an array:
}).get();
This isn't guaranteed to be in numerical order, though it will be in order of the appearance of those elements in the DOM.
References:
Attribute-starts-with ([attribute^=value]) selector.
get().
map().
Simply, you can do the following:
var port = Array();
for (i = 0; i < 5; i++){
port[i] = $("#slcPort_"+i).val();
}
DEMO: http://jsbin.com/yiyaruweja/1/
It might make more sense to give all those elements a class, like slcPort. Then something like
var port = [];
$.each($('.slcPort'), function(index,value) {
port[index] = $(value).val();
});
Much prettier. Plus all those elements are related anyways, so just class em up.
$.each documentation

Categories

Resources