I'm currently trying to create an object to be used in a JSON request, based on the controls on the page and their values.
I'm using the jQuery map() function to get the keys and values out of the controls like so
var data = $("fieldset > div.section").map(function (i, e) {
var result = {};
result[e.children[0].id.substring(3);] = e.children[1].value;
return result;
}).get();
This gets the data I'm after, but I end up with nested objects rather than an array, this looks like so
[{"ClientId":"123456"},{"ClientIdType":"5"},{"City":"Brisbane"},{"Sex":"10"},{"PostCode":"4064"},{"State":"QLD"}]
But what I want is something like
{"ClientId":"123456","ClientIdType":"5","City":"Brisbane","Sex":"10","PostCode":"4064","State":"QLD"}
Is there a way to do this in one go, or should I just iterate over the array again to flatten it?
This is a case for each() not map():
var data = {};
$("fieldset > div.section").each(function (i, e) {
data[e.children[0].id.substring(3)] = e.children[1].value;
});
Related
I have this result in my script
'[{"region":"NCA","depprt":"Havana, Cuba"},{"region":"NCA","depprt":"Havana, Cuba"},{"region":"NCA","depprt":"Montego Bay, Jamaica"},{"region":"NCA","depprt":"Montego Bay, Jamaica"}]'
this is the code to get it.
var jsonList = '#Html.Raw(Json.Encode(ViewBag.chk))'
var jsList = JSON.stringify(jsonList);
for jsList I got above result.now I want to get all depprt where region is equal to NCA.how can I do that.
You can use the .filter() method for this.
var ncaList = jsonList.filter(function(obj){ return obj.region == "NCA"; });
Very simple. Iterate over the jList array and see if the region property matches your condition or not then append the item to your filtered array.
var filtered = [];
jList.forEach(function(item) {
if(item.region == 'NCA') {
filtered.push(item);
}
});
Just iterate over it:
var filteredDepprts = [];
jsList.forEach(function(element){
if(element.region == 'NCA'){
filteredList.push(element.depprt); //or element if you want to push the full object
}
});
The JSON.stringify method converts a JavaScript value to a string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
When you want to convert a JSON string to a JavaScript value, use JSON.parse
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var jsonList = '#Html.Raw(Json.Encode(ViewBag.chk))'
var jsList = JSON.parse(jsonList);
Using single quotes around your #Html.Raw, creates a string and not a JavaScript value. The filter method does not work on strings
Eventually you could use Array.prototype.filter Filter out each element in array, that matches your criteria.
https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Try map:
var obj= [];
for (i in jsonList) {
if (jsonList[i].region == "NCA") { obj.push(jsonList[i])};
}
https://jsfiddle.net/pd6hvn78/
I'm trying to create an array in Javascript with a size that is equivalent to the number of times a certain class is found in the DOM, and then iterate through it to grab the text from an input field present in that class. I can easily do this like so:
var count = 0;
$('.className').each(function() {
count++;
});
var classes = new Array(count);
count = 0;
$('.className input[type=text]').each(function() {
classes[count++] = $(this).val();
});
This looks like a lot of code for what seems to be a relatively simple task. Is there a more efficient or less lengthy way of doing this?
Thanks
It looks like you want this :
var classes = $('.className input[type=text]').map(function(){
return this.value
}).get();
But it's a guess : it's not clear why you start by counting all elements of the class and then iterate on the inputs.
You can construct an array of elements directly from your selector via the makeArray function, then transform the result using a map.
var classes = $.makeArray($('.className input[type=text]')).map(function() {
return $(this).val();
});
Use jQuery's map function, then get if you need a pure array:
var values = $('.className input[type=text]').map(function() {
return $(this).val();
}).get();
each passes the index, so you don't need to do it yourself:
var classes = [];
$('.className input[type=text]').each(function(index, value) {
classes[index] = $(this).val();
});
Arrays are dynamic and therefore don't need to be initialized. Create a new array, loop through the inputs and push the values to the new array:
var classes = [];
$('.className input[type=text]').each(function(idx, elem) {
classes.push($(elem).val());
});
I currently the following jQuery collection / object:
[li.row-0, li.row-1, li.row-2, li-row-2, li.row-2, li.row-3]
Each class name is dynamically added to each element by a previous method. The only consistent part of the class name is row-. The number can be anywhere from 0 - ∞.
I want to create a new array or object of elements that are grouped by same dynamic class name:
[li.row-0]
[li.row-1]
[li.row-2, li.row-2, li.row-2, li.row-2]
[li.row-3]
The above is just a guess of the outcome, as I am not 100% sure how best to achieve this.
The aim is to be able to loop through .row-0, .row-1, .row-2, .row-3 and do something with the elements in each individual row.
I would do this :
var map = [].reduce.call(arr, function(map, v){
(map[v.className]||(map[v.className]=[])).push(v);
return map;
}, {});
var arr2 = [];
for (var className in map) arr2.push(map[className]);
The reduce builds a map having as keys the class names and with values the arrays of the elements having that class name.
I use [].reduce.call(arr, instead of arr.reduce( so that it works for standard arrays, jQuery collections, nodelists, etc.
Then the loop builds an array from that map. You might find the map more useful than the final array.
This shows you a general way of achieving this, though you're probably using elements rather than strings, but hopefully this will help
var tst = ['li.row-0','li.row-1','li.row-2','li.row-2','li.row-2','li.row-3'];
var grouped = [];
for(var i in tst)
{
var text = tst[i];
var num = text.replace('li.row-','');
if(!grouped[num]) grouped[num] = [];
grouped[num].push(text);
}
console.log(grouped);//[["li.row-0"], ["li.row-1"], ["li.row-2", "li.row-2", "li.row-2"], ["li.row-3"]]
Using elements:
var tst = [li.row-0,li.row-1,li.row-2,li.row-2,li.row-2,li.row-3];
var grouped = [];
for(var i in tst)
{
var text = tst[i].className;
var num = text.replace('row-','');
if(!grouped[num]) grouped[num] = [];
grouped[num].push(text);
}
console.log(grouped);//[["li.row-0"], ["li.row-1"], ["li.row-2", "li.row-2", "li.row-2"], ["li.row-3"]]
This method is more verbose and allows more complex grouping if need be (if other attributes come into play)
I would do something like the following:
var arr = ['li.row-0', 'li.row-1', 'li.row-2', 'li.row-2', 'li.row-2', 'li.row-3'];
var result = {};
$.each(arr, function (index, item) {
var ind = item.toString().split('row-')[1];
(result[ind] || (result[ind] = [])).push(item);
});
console.log(result);
I might have written a pretty confusing title but my question is rather simple.
I'm looking for an efficient way to remove an item from an array. But my array is full objects that has been stringified (I'm writing my app on Node.js and I'm using JSON.stringify method). So my array is like this;
"{\"userID\":\"15\",
\"possibleFollowers\":[
{\"followerID\":\"201\",\"friends\":716},
{\"followerID\":\"202\",\"friends\":11887},
{\"followerID\":\"203\",\"friends\":11887}],
\"name\":\"John\",
\"lon\":\"Doe\"}"
My question is on Javascript(or Node). If I wanted to remove the from possibleFollowers with "followerID: 202", how would I be able to do that efficiently?
var string = "…";
var obj = JSON.parse(string);
obj.possibleFollowers = obj.possibleFollowers.filter(function(fol) {
return fol.followerID != "202";
});
string = JSON.stringify(obj);
var data = "{\"userID\":\"15\",\"possibleFollowers\":[{\"followerID\":\"201\",\"friends\":716},{\"followerID\":\"202\",\"friends\":11887},{\"followerID\":\"203\",\"friends\":11887}],\"name\":\"John\",\"lon\":\"Doe\"}";
var dataObject = JSON.parse(data);
dataObject.possibleFollowers = dataObject.possibleFollowers.filter(function(follower) {
return !(follower.followerID == "202");
});
data = JSON.stringify(dataObject);
In javascript, the splice method is used to delete an array element by index.
see :
http://www.roseindia.net/java/javascript-array/javascript-array-remove-index.shtml
try just to delete it by using "delete"
for (var i in possibleFollowers) {
if (possibleFollowers[i]['followerId'] == '216') {
delete possibleFollowers[i];
}
}
I have an array inside an $.each function. I want to iterate through it to create a new or modified array. But I need to access the $(this) from the outside $.each loop:
// target these data attributes:
$selector = $('[data-my0], [data-my1], [data-my2]');
$.each($selector, function() {
var $this = $(this), // cache selector
keys = ['my0', 'my1', 'my2']; // array of data keys
// I want to use the keys array to make a vals array to this:
// var vals = [$this.data('my0'), $this.data('my1'), $this.data('my2')];
// This doesn't seem to work (can't read from length 0 error):
var vals = $.map( keys, function( key ) { return $this.data(key); });
});
I think it's possible to do this using using $.each or $.map but this is where I'm stuck. I know $(this) not used normally with $.map like it is with $.each. In this case, I'm trying to pass the $this from the outside that represents the selector.
Wait - you're passing "vals" into your "$.map()" cal instead of "keys":
var vals = $.map( keys, function( key ) { return $this.data(key); });
Here is a jsfiddle. The code works just fine, though without seeing your actual HTML it's hard to know exactly what you expect to happen.