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'.
Related
I have to create cart system in my mobile application, i want to store the id and the quantity of products, the id should be the key of my array (for modifying product quantity) , tried to use object instead of array but i get error: undefined is not a function when i try to read my json variable
by JSON.stringify(cart)
My cart code is like this
var cart = [];
var produit = {};
produit['qte'] = $('.'+id_prd).text();
produit['id_produit'] = id_prd;
cart[id_prd] = produit;
window.sessionStorage["cart1"]= JSON.stringify(cart);
return me
{"7":{"qte":"1","id_produit":7},"8":{"qte":"1","id_produit":8}}
when I tried to parse the json string with
var parsed = $.parseJSON(window.sessionStorage["cart1"]);
i get the error 'undefined is not a function'
when triying to read the json with
var i=0;
for (k in parsed) {
var k_data = parsed[k];
k_data.forEach(function(entry) {
alert(entry);
ch+=entry.id_produit;
if(i<parsed.length-1)
ch+= ',';
if(i==parsed.length-1)
ch+=')';
i++;
});
}
Can you clarify me the error cause, and if there's a solution to better read the json
The problem is that you are using k_data.forEach(function(entry) but forEach is for Arrays, and k_data is just a simple javascript object.
Try changing:
k_data.forEach(function(entry){
to this:
$(k_data).each(function(entry){
Even more, if the JSON is always in the same structure you posted, I think the each function is not necessary, maybe this is the way you are looking for:
var i=0;
var ch = "(";
for (k in parsed) {
var k_data = parsed[k];
alert(k_data);
ch+=k_data.id_produit;
ch+= ',';
i++;
}
ch = ch.substring(0, ch.length - 1) + ")";
You shouldn't need jQuery for this. The same JSON object you used to stringify has a parse function:
var parsed = JSON.parse(window.sessionStorage["cart1"]);
If that still breaks, there's probably something wrong with another undefined object.
You can try something like this:
<script type="text/javascript">
var finalArr = new Array();
var dataArr = new Array();
dataArr = window.sessionStorage["cart1"];
if (JSON.parse(dataArr).length > 0) {
for (var i = 0; i < JSON.parse(dataArr).length; i++) {
finalArr.push((JSON.parse(dataArr))[i]);
}
}
</script>
I'm trying to parse something like this
{
"popular result":[
{"term":"Summer","url":"http://summer.com"},
{"term":"Autumn","url":"http://autumn.com"},
{"term":"spring","url":"http://spring.com/"},
{"term":"winter","url":"http://winter.com/"}]
}
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i = 0; i < json.length; i++) {
$.each(myJson.i, function (key, value) {
alert(value.term);
});
}
});
});
</script>
but nothing happened! Because is array in array! Please let me know how to do this
Arrays and objects are different things. You will want to investigate them tons more before things get really challenging.
Assuming json really does equal the object you provide (in JSON those show up as {}), then json['popular result'] (you could use a . if there wasn't a space) is the array (in JSON those show up at []) you want to traverse.
For some reason, this confusion got you looping over an object (not going to get you anywhere as length is rarely defined for it) and then (ignoring the typo on myJson), you started looping over something that didn't exist (which didn't crash b/c it never got there).
Cleaning it up...
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i=0;i<json['popular result'].length;i++) {
alert(json['popular result'][i].term + ' points to the URL ' + json['popular result'][i].url);
}
});
});
</script>
Notice how the alert references the json object (that's your variable name), the popular result array, then [i] is the "row" in that array, and the term/url element of the object on that row.
NOTE: Running something with a ton of alerts as you're debugging is annoying. Check out console.log.
You don't need $.each and you need to loop over the array set as the value of popular result which is inside a containing object.
$.getJSON('/Controls/GetPopularSearches', function (json) {
var arr = json['popular result'];
for (var i = 0, l = arr.length; i < l; i++) {
console.log(arr[i].term);
}
});
Demo.
Check this fiddle
var jsontext =
'{"popularresult":[{"term":"Summer","url":"http://summer.com"},{"term":"Summer","url":"http://summer.com"}]}';
var getContact = JSON.parse(jsontext);
for (i = 0; i < getContact.popularresult.length; i++) {
alert(getContact.popularresult[i].term);
}
http://jsfiddle.net/ae8gd/
If you get the jsonObject as shown then
var JsonArray=json.popular; //get jsonArry
$.each(JsonArray,function(i,val){
// do logic
});
To parse json use JSON.parse();
I am stuck here. How can I clean this array:
{"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
So that it looks like:
["5201521d42","52049e2591","52951699w4"]
I am using Javascript.
You just need to iterate over the existing data array and pull out each id value and put it into a new "clean" array like this:
var raw = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean = [];
for (var i = 0, len = raw.data.length; i < len; i++) {
clean.push(raw.data[i].id);
}
Overwriting the same object
var o = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for (var i = o.data.length; i--; ){
o.data[i] = o.data[i].id;
}
What you're doing is replacing the existing object with the value of its id property.
If you can use ES5 and performance is not critical, i would recommend this:
Edit:
Looking at this jsperf testcase, map vs manual for is about 7-10 times slower, which actually isn't that much considering that this is already in the area of millions of operations per second. So under the paradigma of avoiding prematurely optimizations, this is a lot cleaner and the way forward.
var dump = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var ids = dump.data.map(function (v) { return v.id; });
Otherwise:
var data = dump.data;
var ids = [];
for (var i = 0; i < data.length; i++) {
ids.push(data[i].id);
}
Do something like:
var cleanedArray = [];
for(var i=0; i<data.length; i++) {
cleanedArray.push(data[i].id);
}
data = cleanedArray;
Take a look at this fiddle. I think this is what you're looking for
oldObj={"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
oldObj = oldObj.data;
myArray = [];
for (var key in oldObj) {
var obj = oldObj[key];
for (var prop in obj) {
myArray.push(obj[prop]);
}
}
console.log(myArray)
Use Array.prototype.map there is fallback code defined in this documentation page that will define the function if your user's browser is missing it.
var data = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean_array = [];
for( var i in data.data )
{
for( var j in data.data[i] )
{
clean_array.push( data.data[i][j] )
}
}
console.log( clean_array );
You are actually reducing dimension. or you may say you are extracting a single dimension from the qube. you may even say selecting a column from an array of objects. But the term clean doesn't match with your problem.
var list = [];
var raw = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for(var i=0; i < raw.data.length ; ++i){
list.push(raw.data[i].id);
}
Use the map function on your Array:
data.map(function(item) { return item.id; });
This will return:
["5201521d42", "52049e2591", "52951699w4"]
What is map? It's a method that creates a new array using the results of the provided function. Read all about it: map - MDN Docs
The simplest way to clean any ARRAY in javascript
its using a loop for over the data or manually, like this:
let data = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},
{"id":"52951699w4"}]};
let n = [data.data[0].id,data.data[1].id, data.data[2].id];
console.log(n)
output:
(3) ["5201521d42", "52049e2591", "52951699w4"]
Easy and a clean way to do this.
oldArr = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
oldArr = oldArr["data"].map(element => element.id)
Output: ['5201521d42', '52049e2591', '52951699w4']
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
$('#div1').append(msgid);
$('#div2').append(rspid);
});
Let's say the value of newitems is [["320","23"],["310","26"]]
I want to assign "320" and "310" to var msgid.
I want to assign "23" and "26" to var rspid.
How to do that?
I tried to display newitems and the output is "Array". I tried to display newitems[0] and the output is blank.
If I redeclare var newitems = [["320","23"],["310","26"]]; it works. So I guess the variable newitems from jQuery.get is something wrong. Is it I cannot pass the array from other page to current page through jQuery directly?
Regarding the array on other page, if echo json_encode($Arraytest); the output is [["320","23"],["310","26"]] but if echo $Arraytest; the output is Array. How do I pass the array from other page to currently page by jQuery.get?
I don't totally understand the question but I'm going to assume you want the values in an array, as two values can't be stored in one (scalar) variable simultaneously.
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
var msgid = [],
rspid = [];
for( i = 0 ; i < newitems.length ; i++){
msgid[msgid.length] = newitems[i][0];
rspid[rspid.length] = newitems[i][1];
}
//msgid now contains ["320","310"]
//rspid now contains ["23","26"]
});
Bear in mind those are in the function scope. If you want to use them outside of that scope instantiate them outside. see: closure
You can use pluck from underscore.js: http://documentcloud.github.com/underscore/#pluck
var msgid = _(newitems).pluck(0)
var rspid = _(newitems).pluck(1)
Try this:
function getArrayDimension(arr, dim) {
var res = [];
for(var i = 0; i < arr.length; i++) {
res.push(arr[i][dim]);
}
return res;
}
var newitems = [["320","23"],["310","26"]];
var msgid = getArrayDimension(newitems, 0);
var rspid = getArrayDimension(newitems, 1);
msgid and rspid are arrays holding the 'nth' dimention.
Tnx
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]; });