Solved

Creating an array of object from a string or an array

Posted on 2014-10-22
23
117 Views
Last Modified: 2014-10-24
I need to create an array of objects from a string or an array.

I nitially had the attached function which is totally wrong.

The string I pass in is something like this: itemHeader="Engine,Browser,Platform,Version,Grade"

It needs to be output the following way:
{ "sTitle": "Engine" },      
{ "sTitle": "Browser" },      
{ "sTitle": "Platform" },      
{ "sTitle": "Version" },      
{ "sTitle": "Grade" },
                    
Thanks for any help you can provide
function createTableHeader(itemHeader)
{

    var items = itemHeader.split(",");

	var DTColumn = {};
	var DTCarray = [];
	
	for (x=0; x<items.length; x++)
	{
			DTColumn = "{\"sTitle\":"+" "+items[x]+"}";
			DTCarray.push(DTColumn.Title,);		
	}
	return DTCarray;	
}

Open in new window

0
Comment
Question by:Isaac
  • 13
  • 10
23 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 40397962
test page : http://jsfiddle.net/2k1oyygb/
function createTableHeader(itemHeader) {
    return itemHeader.split(/[,"]/).slice(1,-1);
}

Open in new window

0
 
LVL 5

Author Comment

by:Isaac
ID: 40397981
I need to use it with the datatable jquery plugin, specifically for the 'aoColums'. It only takes an array of objects.  Will what you have work?
0
 
LVL 5

Author Comment

by:Isaac
ID: 40397985
It does not play nice with strings
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 82

Expert Comment

by:leakim971
ID: 40397989
I don't know, just answered your main question, try it.
0
 
LVL 5

Author Comment

by:Isaac
ID: 40400409
It does not work because it's a string.

My main question says

It needs to be output the following way:
{ "sTitle": "Engine" },      
{ "sTitle": "Browser" },      
{ "sTitle": "Platform" },      
{ "sTitle": "Version" },      
{ "sTitle": "Grade" },

Check out this page and click on "aaData", third from the top of the table.  As you will see, "aaColumns" accepts an array of objects which is what I need.  Not a string.

Any ideas?

Thanks!
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40400423
function createTableHeader(itemHeader) {
    var strings = itemHeader.split(/[,"]/);
    var arr = [];
    for(var i=1;i<strings.length-1;i++) {
        var obj = { "sTitle" : strings[i] };
        arr.push(obj);
    }
    return arr;
}

Open in new window

0
 
LVL 5

Author Comment

by:Isaac
ID: 40400447
what's the difference between

 itemHeader.split(/[,"]/);

and

 itemHeader.split(",");
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40400456
did it work?
0
 
LVL 5

Author Comment

by:Isaac
ID: 40400594
No.

Object
0
 
LVL 5

Author Comment

by:Isaac
ID: 40400600
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40400625
The string I pass in is something like this: itemHeader="Engine,Browser,Platform,Version,Grade"

now I see :
var string = "Test,Ink,Test2,Test3,Test4";

anyway with the new string :
http://jsfiddle.net/ffjo9tcx/2/
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40400626
var string = "Test,Ink,Test2,Test3,Test4";
alert(JSON.stringify(createTableHeader(string)));

function createTableHeader(itemHeader) {
    var strings = itemHeader.split(",");
    var arr = [];
    for(var i=0;i<strings.length;i++) {
        var obj = { "sTitle" : strings[i] };
        arr.push(obj);
    }
    return arr;
}

Open in new window

0
 
LVL 5

Author Comment

by:Isaac
ID: 40400637
It doesn't matter what is being passed in.  It will always be comma delimited.  Sorry for the confusion.

The results of arr will be eventually passed into the function below as tHeader.  It will be used for "aoColumns" parameter.

function CreateDataTable(tableID, sortCols, tHeader, tCells)
{

	var myDataTable = $(tableID).dataTable({
		"sScrollY": "auto",
		"bDestroy": true,
		"bPaginate": true,
		"bProcessing": true,
		"aaData": [tCells],
		"aoColumns": [tHeader],
		
		"sPaginationType": "full_numbers",
		"iDisplayLength": (defaultDrillDownLength || 10),
		"aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
		"sDom": '<"topPagination"ilp>frt<"bottomPagination"p>',
		/*"aoColumnDefs": [
      		{ "bSortable": false, "aTargets": [ "non-sortable" ] }, {"bVisible":false, "aTargets": [ "filterable" ] }
    	],*/
    	"aaSorting": (sortCols ? sortCols : [[0,'asc']]),  
		"oLanguage": {
			"sInfoFiltered": ""
		},
		//turning bSortClasses off should be a performance boost for large datasets. disable the addition of the classes 'sorting_1', 'sorting_2' and 'sorting_3' to the columns which are currently being sorted on
		"bSortClasses": false
	});
}

Open in new window


I will try what you have and see if it works.
0
 
LVL 5

Author Comment

by:Isaac
ID: 40400678
It did not work because it's a string and not an object.

Here's the alert:
object
Here's my table and as you can see, no headers bc it's a string
table
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40400714
where are you seing a string?
0
 
LVL 5

Author Comment

by:Isaac
ID: 40400725
jsonstringfy()
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40400730
we have an alert too... are you going to let the alert too ?
jsonstringfy is to display the object
0
 
LVL 5

Author Comment

by:Isaac
ID: 40400735
When I hard code the "aocolumns" like this
headersThe aocolumns is an array of objects

I get this:
table
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 40400789
function createTableHeader(itemHeader) {
    var strings = itemHeader.split(/[,"]/);
    var arr = [];
    for(var i=1;i<strings.length-1;i++) {
        var obj = { "sTitle" : strings[i] };
        arr.push(obj);
    }
    return arr;
}
var tHeader = createTableHeader("Engine,Browser,Platform,Version,Grade,Engine,Browser,Version,Grade,Grade");

Open in new window

and use this :
"aoColumns": tHeader,

Open in new window

not this :
"aoColumns": [tHeader],

Open in new window

0
 
LVL 5

Author Comment

by:Isaac
ID: 40400810
Here's the  value of tHeader:
tbl
Here's the code:
var myDataTable = $(tableID).dataTable({
		"sScrollY": "auto",
		"bDestroy": true,
		"bPaginate": true,
		"bProcessing": true,
		"aaData": tCells,
		"aoColumns": tHeader,
		/*"aoColumns": [    
	  				{ "sTitle": "Engine" },       
	  				{ "sTitle": "Browser" },       
	  				{ "sTitle": "Platform" },       
	  				{ "sTitle": "Version" },       
	  				{ "sTitle": "Grade" }, 
	  				{ "sTitle": "Engine" },       
	  				{ "sTitle": "Browser" },       
	  				{ "sTitle": "Platform" },       
	  				{ "sTitle": "Version" },       
	  				{ "sTitle": "Grade" },     
	  				{ "sTitle": "Grade" }  
	  			],*/
		"sPaginationType": "full_numbers",
		"iDisplayLength": (defaultDrillDownLength || 10),
		"aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],

Open in new window


Here's the output:
tbl modal
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40400821
use the hard code way too, setup a jsfiddle when you've time (with hard coded)
http://jsfiddle.net
0
 
LVL 5

Author Comment

by:Isaac
ID: 40402971
Ok.  I took your advice and put it in jsfiddle and it worked so what you provided worked.  Thanks!

I will post another problem though and provide you the link to it on the same code.
0
 
LVL 5

Author Closing Comment

by:Isaac
ID: 40402972
Thanks for your patience.
0

Featured Post

The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to refresh a page from a sub domain in ajax ? 34 23
jQuery dialog box help 2 17
Running a javascript project in WebStorm 2 28
HTML Anchor Link Problem 3 37
Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question