PDA

View Full Version : Manipulating javscript Objects and Arrays



tomalex0
14 Oct 2010, 2:46 AM
Hi,

I was trying to generate an array from another set of Objects



var testdata=[{"id":1,"date":"2010-10-07","starttime":"10:30","endtime":"11:30"},{"id":2,"date":"2010-10-08","starttime":"11:30","endtime":"12:30"},{"id":3,"date":"2010-10-07","starttime":"9:30","endtime":"10:30"},{"id":4,"date":"2010-10-08","starttime":"11:30","endtime":"12:30"},{"id":5,"date":"2010-10-07","starttime":"14:30","endtime":"16:30"},{"id":6,"date":"2010-10-08","starttime":"13:30","endtime":"14:30"}];
var testarr =new Array();
var testobj = new Object();
Ext.each(testdata,function(record,i){
//console.log(testobj+'.'+eval("record.date")) ;
//console.log(eval('testobj['+eval("test1")+"] = 2")) ;
console.log(eval('testobj['+test1+"] = "+record.id)) ;
})
console.log(testobj);


Can i get something like as mentioned below
Output


{"2010-10-07":[1,3,5],"2010-10-08":[2,4,6]}

VinylFox
14 Oct 2010, 4:14 AM
Just a few notes on your code...

The shorthand of {} and [] for creating objects and arrays is simpler and has no downsides...less to type.


var testarr =new Array();
var testobj = new Object();

There is no reason to use eval in this situation. There are actually very few cases where you would need to use eval in your code, so throwing it around in your code like this is concerning to me.


//console.log(testobj+'.'+eval("record.date")) ;
//console.log(eval('testobj['+eval("test1")+"] = 2")) ;
console.log(eval('testobj['+test1+"] = "+record.id)) ;


Try this instead...


// initialize the variable with an empty object
var testobj = {};
Ext.each(testdata,function(record,i){
// create an empty array in the position of the date if the date does not exist yet
testobj[record.date] = testobj[record.date]||[];
// add the id number to the array associated with that date
testobj[record.date].push(record.id);
})
console.log(testobj);

jay@moduscreate.com
14 Oct 2010, 5:20 AM
There is no reason to use eval in this situation. There are actually very few cases where you would need to use eval in your code, so throwing it around in your code like this is concerning to me.


+1

tomalex0
14 Oct 2010, 5:24 AM
Thanks for the valuable help, i was trying in the wrong way. As you said i was using evals all over. Your code made things simple.

Thanks again