TrySpace
TrySpace

Reputation: 2460

Convert Array-String to Object with Javascript or jQuery

I'm listing every DOM element's id on the page with:

 var listy = $("*[id]").map(function(){
    return this.id;
 }).get().join(',');

So, example output of listy would be:

"home,links,stuff,things"

Now I want to convert the listy Array to an Object, like:

function toObject(arr) {
    var rv = {};
    for (var i = 0; i < arr.length; ++i)
        if (arr[i] !== undefined) rv[i] = arr[i];
    return rv;
}

But that wil put everything it in an Object like:

0: "h", 1: "o", 2: "m", etc...

What I obviously want is:

0: "home", 1: "links, 2: "stuff", etc..

Where am I going wrong, I got the toObject() from: Convert Array to Object

Which brings me to a similar, but different question:

Indexing page elements to JSON object? Or jQuery selector it every time?

Upvotes: 3

Views: 13818

Answers (5)

muthu
muthu

Reputation: 11

my code:

jQuery.ajax({
        type: 'POST',                    
        url:'../pages/HomePage.php',            
        data:{param  : val},
        dataType:'HTML',                
        success: function(data)
        {
            var data = data ;
            obj = {};



             $.each(data.split(','), function(k, v) {
                 obj[k]= v;
            alert("success"); 

         $("#process_des").val(obj[0]);
             });

        }
    }); 

my output

Array
(
    [0] => FILLET SKIN OFF
    [1] => SF
)

Upvotes: 1

Robert Koritnik
Robert Koritnik

Reputation: 105029

This is likely the shortest code you can write to get your object:

// your existing code (a tiny bit changed)
var idArray = $("*[id]").map(function() {
    return this.id;
}).get();

// this one liner does the trick
var obj = $.extend({}, idArray);

A better approach for your problem - associative array

But as I've read in your comments in other answers this object structure may not be best in your case. What you want is to check whether a particular ID already exists. This object

{
    0: "ID1",
    1: "otherID",
    ...
}

won't help too much. A better object would be your associative array object:

{
    ID1: true,
    otherID: true,
    ...
}

because that would make it simple to determine particular ID by simply checking using this condition in if statement:

if (existingIDs[searchedID]) ...

All IDs that don't exist would fail this condition and all that do exist will return true. But to convert your array of IDs to this object you should use this code:

// your existing code (a tiny bit changed)
var idArray = $("*[id]").map(function() {
    return this.id;
}).get();

// convert to associative "array"
var existingIDs = {};
$.each(idArray, function() { existingIDs[this] = true; });

or given the needed results you can optimise this a bit more:

var existingIDs = {};
$("*[id]").each(function() { existingIDs[this.id] = true; });

This will speed up your existing ID searching to the max. Checking ID uniqueness likely doesn't need hierarchical object structure as long as you can get the info about ID existence in O(1). Upper associative array object will give you this super fast possibility. And when you create a new object with a new ID, you can easily add it to existing associative array object by simply doing this:

existingIDs[newID] = true;

And that's it. The new ID will get cached along with others in the same associative array object.

Caution: I can see your code has implied global (listy variable). Beware and avoid if possible.

Performance testing

As @Blazemonger suggests this doesn't hold water I'd say that this claim may be true. It all boils down to:

  • the number of elements with IDs you have
  • number of searches you'd like to do

If the first one is normally low as in regular HTML pages where CSS classes are more frequently used than IDs and if the second one is large enough then this performance test proves that associative array can be a fair bit faster than using jQuery alone. HTML Used in this test is a copy of Stackoverflow's list of questions on the mobile site (so I had less work eliminating scripts from the source). I deliberately took an example of a real world site content than prepared test case which can be deliberately manufactured to favour one or the other solution.

If you're searching on a much smaller scale, than I using straight forwards jQuery would be faster because it doesn't require start-up associative array preparation and gets off searching right away.

Upvotes: 3

Ryan
Ryan

Reputation: 3815

Check this out http://jsfiddle.net/ryan_s/XRV2m/

It will

  1. Create a cache to store id's of existing elements so you don't get a performance overhead each time you want to generate a new id.
  2. Auto Generate an incremental id based upon the tag name you pass to it.
  3. Update the cache if you really plan on using the id's.

I am just printing the id's on the console for convenience.

Just my 2 cents based on some of your earlier comments to other's replies.

Upvotes: 1

Blazemonger
Blazemonger

Reputation: 92893

Your listy is a string, not an array. Change your first block of code to this:

 listy = $("*[id]").map(function(){
    return this.id;
 }).get();

http://jsfiddle.net/P7YvU/

As for creating an object indexing the entire document: for what purpose? There is little advantage to doing this yourself when you can just parse the DOM directly -- especially since jQuery makes it so easy. Instead of calling DOMJSONTHING.body.div.h1 to get the value "home", you can already call $('document > body > div > h1').attr('id') and get the same result.

Upvotes: 5

thecodeparadox
thecodeparadox

Reputation: 87073

var str = 'home,links,stuff,things',
    obj = {};

$.each(str.split(','), function(index, val) {
    obj[index] = val;
});

DEMO

Upvotes: 2

Related Questions