Convert Array-String to Object with Javascript or jQuery

13,621

Solution 1

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.

Solution 2

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.

Solution 3

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

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

DEMO

Solution 4

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
)

Solution 5

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.

Share:
13,621
TrySpace
Author by

TrySpace

I am

Updated on June 06, 2022

Comments

  • TrySpace
    TrySpace almost 2 years

    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?

  • TrySpace
    TrySpace almost 12 years
    I just want to have all the elements in an object, monitor that object with, I think, .watch, and when the object changes, modify the DOM...
  • TrySpace
    TrySpace almost 12 years
    And, I don't want to call the jQuery selector every time, to save resources. Beacause I want to cache the DOM structure, so I can read/write it.
  • Blazemonger
    Blazemonger almost 12 years
    The amount of overhead consumed by jQuery when searching the DOM, is probably less than the amount of overhead you'll consume building your object in the first place. Computers are fast these days. Your object also assumes that every single element will have a unique ID, which might not be the case. This is a case of premature optimization, trying to save cycles before you even have reason to think you'll need to.
  • TrySpace
    TrySpace almost 12 years
    What if I want to change the 0, 1, 2 index of the Object to correspond to the element.tagName, so, assigning 'this' to the object index. Also then, how to prevent it from creating duplicate Object indexes, but grouping each element under a tag node?
  • thecodeparadox
    thecodeparadox almost 12 years
    @TrySpace object does not allow duplicate keys. If you try to do that last value will remain. Suppose var x = {a: 'abc'} and then if you try x.a = 'def', then result will be x= {a: 'def'};
  • TrySpace
    TrySpace almost 12 years
    Thing is.. I want to make this Object to check if an ID already exists and then rename it, before I create an element...
  • Blazemonger
    Blazemonger over 11 years
    So do that on demand, rather than doing it ahead of time. Again: there's no reason not to.
  • Robert Koritnik
    Robert Koritnik over 11 years
    @Blazemonger: I think you're wrong. jQuery selectors can never outpace cached objects... Because when creating an object OP is only required to run one jQuery selector and create the object. Afterwards no element selection is needed any more. A super fast associative array check will always be faster than jQuery element selection. It is a different matter if OP used array-like object (index properties) because searching for existing IDs does iterate the object and has O(n/2) complexity. Associative array check has O(1) which is fastest possible.
  • Blazemonger
    Blazemonger over 11 years
    @RobertKoritnik Caching a single object which is used frequently is one thing. Caching EVERY SINGLE object on the page because you MIGHT use it is another. The second approach, in the end, will probably be more processor-intensive and devour more memory than if you'd done nothing at all. The speed gains of your associative-array check are outweighed by the time spent building the array in the first place. It's like driving your car ten miles out of the way to save two cents per gallon on gas -- in the end, you're spending more than you're saving.
  • Robert Koritnik
    Robert Koritnik over 11 years
    @Blazemonger: It of course all depends on the number of these comparisons and complexity of the document and amount of elements with IDs, but check this performance test.
  • Robert Koritnik
    Robert Koritnik over 11 years
    And what exactly do you mean by caching every single object on the page? We're talking about one object here. An associative array of IDs. No other object. I+ve also edited my answer to include performance test data and a bit of explanation. The thing is we're both right. It depends on the case...
  • Blazemonger
    Blazemonger over 11 years
    @RobertKoritnik I mean "every single DOM element", just as the OP described. Even if it isn't slower, the millisecond gains MIGHT only be noticeable in the most complex of web applications or the slowest browsers. It's a classic case of premature optimization, and I see no reason to recommend it.