Reverse object in jQuery.each - javascript

HTML:
<input id="sdata" type="hidden" value='{"1651":["12","1"],"1650":["30","0"],"1649":["20","0"],"1648":["13","2"],"1647":["11","0"],"1646":["10","0"],"1645":["12","0"],"1644":["8","0"],"1643":["16","1"],"1642":["10","1"],"1641":["10","0"],"1640":["18","3"]}' />
JS:
var data = $.parseJSON($('#sdata').val());
$.each(data, function(id, sc) {
alert(id);
}
OUT: 1640, 1641, 1642, ..., 1651
How to make it in reverse order (ex. 1651, 1650...)?

As it is, you can't in any reliable manner. Because you are enumerating an Object, there is never a guaranteed order.
If you want a guaranteed numeric order, you would need to use an Array, and iterate backwards.
EDIT: This will convert your Object to an Array, and do a reverse iteration.
Note that it will only work if all the properties are numeric.
var data = $.parseJSON($('#sdata').val());
var arr = [];
for( var name in data ) {
arr[name] = data[name];
}
var len = arr.length;
while( len-- ) {
if( arr[len] !== undefined ) {
console.log(len,arr[len]);
}
}

There is another solution, a fairly easy one:
$(yourobject).toArray().reverse();
That's it.

I tried this and it worked perfectly for me.
var data = $.parseJSON($('#sdata').val());
$.each(data.reverse(), function(id, sc) {
alert(id);
});
The only change is the "reverse()" in line 2.

If all you need to do is generate some HTML out of your JSON and put generated elements into a container in reverse order you can use jQuery's prependTo method when building your HTML.
var container = $('<div />');
$.each(data, function (key, value) {
$('<div>' + value + '</div>').prependTo(container);
});

For Objects
If you are dealing with an object, reverse() won't work! Instead you can do this to maintain the order.
$.each(Object.keys(myObj).reverse(),function(i,key){
var value = myObj[key];
//you have got your key and value in a loop that respects the order, go rock!
});

You can use javascript function sort() or reverse()
var data = $.parseJSON($('#sdata').val());
data.reverse();
$.each(data, function(id, sc) {
alert(id);
}

I don't know, but for the simple stuff I work with, this function does the job. It doesn't rely on numeric keys. And will flip simple objects top to bottom. I don't understand complex Objects, so I don't know how "robust" it is.
function flipObject(obj){
var arr = [];
$.each(obj, function(key, val){
var temp = new Object;
temp['key'] = key;
temp['val'] = val;
arr.push(temp);
delete temp;
delete obj[key];
});
arr.reverse();
$.each(arr, function(key, val){
obj[val['key']] = val['val'];
});
}

jsonObj = [];
$.each(data.reverse(), function (i, dt) {
jsonObj.push({
'id': dt.id
});

Here's an option that seemed to have worked for me. Hope this helps someone. Obviously only works on simple objects (non-nested) but I suppose you could figure out way to make something more complicated with a little extra work.
var reversed_object = {};
Object.keys(original_object).reverse().forEach(function(key)
{ reversed_object[key] = original_object[key]; });

Related

Remove items from array -by value not working with jQuery

I'm stuck on a simple thing of removing an item(object) from an array in JavaScript. I am also using jQuery.
I'm trying to build RSS feed and for that I'm storing bookmark/favorites functionality in localStorage. I need to add/remove items from loalStorage array as and when user clicks of the glyphicon-star and glyphicon-star-empty respectively.
The problem I'm facing is during unfavoriting an item. i.e: removing object from array. THe user may click on any favorited item(random order) to unfavorite it. For that I need to remove the respective item from localstorage by value as the index may not always be known. I did search for a valid solution using grep and implemented in my code, but it doesn't seem to work for me.
This is what I found and implemented but it doesn't work:
$(document).on('click', '.glyphicon-star', function(){
var y = arr;
var removeItem = obj;
arr = $.grep(arr, function(value) {
return value != obj;
});
localStorage.favorite = JSON.stringify(arr);
console.log(arr);
for (i=0; i<arr.length; i++)
{
console.log(arr[i]);
}
});
Here is the working: Fiddle
fix for your fiddle
arr = $.grep(arr, function(value) {
return JSON.stringify(value) != JSON.stringify(obj);
localStorage.favorite = JSON.stringify(arr);
console.log(arr);
});
demo here
Object comparison is a little bit tricky to achieve, check this post for info and samples: LINK
You can just add that function to your code and edit your $.grep as follows:
arr = $.grep(arr, function(value) {
return isEquivalent(value, obj) === false;
});
Fiddle here

Make all elements in an array lowercase and remove whitespace - using jQuery

I have an array of postcodes that I have created by reading a text file. I would lik eto step through each item in the array and make it lowercase, and remove any whitespace. So far I have the following:
var postCodesCovered = new Array();
$.get('postcodes.txt', function(data){
postCodesCovered = data.split('\n');
});
$.each(postCodesCovered , function(){
$(this).toLowerCase().replace(/\s+/g, '');
});
This doesn't seem to do the trick though. Is it because I am not setting the values back to the array?
Since .get() is async you need to move your code in the success callback, and you don't need to use this.
var postCodesCovered;
$.get('postcodes.txt', function(data) {
postCodesCovered = data.split('\n');
$.each(postCodesCovered, function(index, value) {
postCodesCovered[index] = value.toLowerCase().replace(/\s+/g, '');
});
// Do something with the data here
});
#satpal is right - you need to process your list in the success callback. Each will iterate over the array items but you want to transform them into lowercase so map would be a better choice. Map takes an array and transforms each item returning a new array. See the jQuery.map docs for more info.
var postCodesCovered = [];
$.get('postcodes.txt', function(data) {
postCodesCovered = $.map(data.split('\n'), function(value, index) {
return value.toLowerCase().replace(/\s+/g, '');
});
});
ry this...
var postCodesCovered = new Array();
$.each(postCodesCovered , function(idx, val){
postCodesCovered[idx] = $(this).toLowerCase().replace(/\s+/g, '');
});
function convertArray(CapsArray){
lowcaseArray = [];
for (var i = 0; i <CapsArray.length; i++) {
lowcaseArray.push(CapsArray[i].replace(/\s+/g,"").toLowerCase());
}
return lowcaseArray;
}
The function above should do the job.
var YourLowCaseArray = convertArray(YourCapsArrayHere);

Getting undefined in dropdown from json content

EDIT 2
Check the fiddle - http://jsfiddle.net/SN5zT/2/
Following is the fiddle for which I am not sure why I am getting undefined in dropdown.
My fiddle - http://jsfiddle.net/z6GDj/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = new Array();
$.each(allSportPosition, function (index, value) {
values[index] = value;
});
//alert(values.length);
values.sort();
$.each(values, function (atIndex, atValue) {
sportPositionOptions = sportPositionOptions + '<option value="' + atIndex + '">' + atValue + '</option>';
});
$(sportPositionOptions).appendTo("#player");
} catch (e) {
alert("Parsing error:" + e);
}
$.each is automatically sorting keys to 25,26,27,28 for res.
Please explain the reason of this and why I am getting undefined ?
Let me know If i need to explain it more, I will surely do it :)
EDIT
Please explain the reason why it is getting sorted automatically http://jsfiddle.net/SN5zT/
Try
values.push(value);
instead of
values[index] = value;
Fiddle Link
The following script is working, I also figured out where the "undefineds" came from.
http://jsfiddle.net/z6GDj/3/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try{
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = allSportPosition;
//$.each(allSportPosition, function(index, value) {
// values[index] = value;
//});
//alert(values.length);
$.each(values,function(atIndex, atValue){
sportPositionOptions = sportPositionOptions+'<option value="'+atIndex+'">'+atValue+'</option>';
});
$(sportPositionOptions).appendTo("#player");
}
catch(e){
alert("Parsing error:"+ e);
}
The array is sorted automatically, because the keys are set correctly.
see http://www.w3schools.com/js/js_obj_array.asp. "An array can hold
many values under a single name, and you can access the values by
referring to an index number."
Or: Change the index, and you´re changing the order. (index indicates the order).
The undefined values are created by javascript default, check the last answer in here (How to append something to an array?)
"Also note that you don't have to add in order and you can actually
skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined."
Since you are passing an object to each(), jquery passes the key as the index parameter. In your object, the keys are ranged from 25 to 28. Setting the array using the values[25] on an empty array will expand the array to index 25, with the first 25 elements undefined. Using values.push(value) will append the value at the end of the array.
$.each is doing the following assignment that is why you are getting so many undefined
values[25] = "Forwards (Strickers)"
values[26] = "Midfielders"
values[27] = "Fullbacks (Defenders)"
values[28] = "Goalkeeper"
During $.each browsers will automatically sort the keys if the keys are integer, one way to avoid this is use non integer keys
What you need to do is define your options before you sort them , and then append them to your select:
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '',
parsedJson = JSON.parse(res),
allSportPosition = parsedJson.allSportPosition,
options = new Array();
$.each(allSportPosition, function (index, value) {
options[index] = $('<option></option>', {
value: index,
text: value
});
});
$.each(options, function (index) {
$('#player').append(options[index]);
});
} catch (e) {
alert("Parsing error:" + e);
}
jsfiddle: http://jsfiddle.net/z6GDj/11/

create array using push method

var members = [
['Fred G. Aandahl', '1951-1953', 'North Dakota'],
['Watkins Moorman Abbitt', '1948-1973', 'Virginia'],
];
I need to create like this dynamically, I am using the following code to do that:
var data = new array();
var members = [];
$.each(data, function (i, elem) {
data.push(elem["p_age"], elem["p_name"], elem["p_date"]);
members.push(data);
});
console.log(members);
}
I need to print this values, for that.
for(var x = 0; x < members.length; x++) {
console.log(members[i][0]);
console.log(members[i][1]);
console.log(members[i][2]);
}
so when i try this i get following.
[object][object][object][object][object][object]
I am not sure how is your code working! It has some error's if your already aware of.
Your code should work fine after you change to:-
var data = new Array();//Was an Error in your code
var members = [];
$.each(temp, function (i, elem) {
data.push(elem["p_age"], elem["p_name"], elem["p_date"]);
members.push(data);
});
console.log(members);
for (var x = 0; x < members.length; x++) {
console.log(members[x][0]);//Was an Error in your code
console.log(members[x][1]);
console.log(members[x][2]);
}
Secondly, how does data.push(elem["p_age"], elem["p_name"], elem["p_date"]); works for you? It should give you undefined.
Just to get myself clear I wrote down your code to a fiddle. Have a look.
Try
var members=[];
$.each(data, function(i, elem) {
members.push([elem["p_date"],elem["p_name"],elem["p_date"]]);
});
console.log(JSON.stringify(members))
This looks suspect:
$.each(data, function(i, elem) {
data.push(elem["p_date"],elem["p_name"],elem["p_date"]);
It looks like you're trying to iterate over data, pushing the elements back on to data. I imagine that the $.each() needs to iterate over something else.
I also question why you're pushing elem['p_date'] onto an array twice.
Because it is treating them as objects. Try using toString() method.
Hi use x instead of i for loop.
for(var x=0;x<members.length;x++){
console.log(members[x][0]);
console.log(members[x][1]);
console.log(members[x][2]);
}
It will work.
Not
var data=new array();
but
var data=new Array();
Array's class name is Array, but not 'array'.

jQuery .each help, I want to trim() all the strings in an array

I'm splitting a string into an array, then I want to remove the white space around each element. I'm using jQuery. I'm able to do this successfully with 2 arrays but I know it's not correct. How do I loop thru an array and trim each element so the elements keep that change. Thanks for any tips. Here is my working code using two array. Please show me the correct way to do this.
var arVeh = vehicleText.split("|");
var cleanArry = new Array();
$.each(arVeh, function (idx, val) {
cleanArry.push($.trim(this));
});
Cheers,
~ck in San Diego
You don't even really need the idx or val parameters. This appears to work on jsFiddle:
var cleanVehicles = [];
$.each(vehicleText.split("|"), function(){
cleanVehicles.push($.trim(this));
});
EDIT: Now that I've seen what you're really after, try using map:
var cleanVehicles = $.map(vehicleText.split("|"), $.trim);
I'm going to suggest not using the overhead of jQuery for a simple for-loop...
var arVeh = vehicleText.split("|");
for (var i = 0, l = arVeh.length; i < l; ++i) {
arVeh[i] = $.trim(arVeh[i]);
});
Alternatively, get rid of the whitespace from the beginning, and avoid the need for another loop at all.
var arVeh = $.trim(vehicleText).split(/\s*\|\s*/);
Without 'creating' an array in the javascript code (an array will nevertheless be created in memory)
vehicles = $.map(vehicleText.split("|"), function(e,i) { return $.trim(e) });
var my_arr = [' cats', 'dogs ', ' what '];
$.each(my_arr, function (id, val) {
my_arr[id] = $.trim(val);
});
console.log(my_arr);
This will trim the value and set it to the indexed item.
You don't have to use JQuery. Here is your vanilla solution:
testArray.map(Function.prototype.call, String.prototype.trim);
Function.prototype.call calls trim() on each of the elements of the testArray. As simple as that!
Could you not just do this?
var arVeh = vehicleText.split("|");
$.each(arVeh, function (idx, val) {
arVeh[idx] = $.trim(this);
});
//a simple function
function trimArray(dirtyArray){
$.map(dirtyArray.split("|"), function(idx, val){
return $.trim(this);
});
}
trimArray(vehicleArray);
should do the trick
Or you could use some of the awesome power of javascript and use array.prototype. I'm still a little new at using the .prototype of any object... so this isnt guaranteed to work (but it certainly can be done).
Array.prototype.trim = function (){
$.map(dirtyArray.split("|"), function(idx, val){
return $.trim(this);
});
}
someArray.trim()
You need these two jQuery functions:
1.) iterate through array element with ability to edit items:
http://api.jquery.com/jquery.map/
2.) remove blank spaces from beginning and end of a string:
http://api.jquery.com/jQuery.trim/
Use them this way:
array = $.map(array, function(value) { return value.trim();});
Check this JSFiddle:
https://jsfiddle.net/L00eyL4x/49/

Categories