简体   繁体   English

使用Javascript或jQuery将Array-String转换为Object

[英]Convert Array-String to Object with Javascript or jQuery

I'm listing every DOM element's id on the page with: 我在页面上列出了每个DOM元素的id

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

So, example output of listy would be: 因此,listy的示例输出将是:

"home,links,stuff,things"

Now I want to convert the listy Array to an Object , like: 现在我想将listy Array转换为Object ,如:

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: 但是,它会把它放在一个Object如:

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 我在哪里出错,我得到了toObject()将Array转换为Object

Which brings me to a similar, but different question: 这让我想到了一个类似但不同的问题:

Indexing page elements to JSON object? 将页面元素索引到JSON对象? Or jQuery selector it every time? 或者每次jQuery选择它?

Your listy is a string, not an array. 你的listy是一个字符串,而不是一个数组。 Change your first block of code to this: 将您的第一个代码块更改为:

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

http://jsfiddle.net/P7YvU/ 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. 当你可以直接解析DOM时,自己做这件事几乎没有什么好处 - 特别是因为jQuery让它变得如此简单。 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. 您可以调用$('document > body > div > h1').attr('id')并获得相同的结果,而不是调用DOMJSONTHING.body.div.h1来获取值“home”。

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. 你想要的是检查一个特定的ID是否已经存在。 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语句中使用这个条件检查就可以很容易地确定特定的ID:

if (existingIDs[searchedID]) ...

All IDs that don't exist would fail this condition and all that do exist will return true . 所有不存在的ID都将失败,并且所有存在的ID都将返回true But to convert your array of IDs to this object you should use this code: 但是要将您的ID数组转换为此对象,您应该使用以下代码:

// 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. 这将加快您现有的ID搜索速度。 Checking ID uniqueness likely doesn't need hierarchical object structure as long as you can get the info about ID existence in O(1). 检查ID唯一性可能不需要分层对象结构,只要您可以在O(1)中获取有关ID存在的信息。 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: 当您使用新ID创建新对象时,只需执行以下操作即可轻松将其添加到现有关联数组对象:

existingIDs[newID] = true;

And that's it. 就是这样。 The new ID will get cached along with others in the same associative array object. 新ID将与同一关联数组对象中的其他ID一起缓存。

Caution : I can see your code has implied global ( listy variable). 警告 :我可以看到你的代码隐含了全局( listy变量)。 Beware and avoid if possible. 如果可能,请注意并避免。

Performance testing 性能测试

As @Blazemonger suggests this doesn't hold water I'd say that this claim may be true. 正如@Blazemonger所说这不成立,我会说这个说法可能是真的。 It all boils down to: 这一切归结为:

  • the number of elements with IDs you have 拥有ID的元素数量
  • 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页面,其中CSS类比ID更频繁使用,如果第二个足够大,那么这个性能测试证明关联数组可以比单独使用jQuery快一点。 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). HTML在此测试中使用的是Stackoverflow在移动站点上的问题列表的副本(因此我从源头删除脚本的工作较少)。 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. 如果你的搜索范围要小得多,那么使用直接向前jQuery会更快,因为它不需要启动关联数组准备并立即开始搜索。

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

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

DEMO DEMO

Check this out http://jsfiddle.net/ryan_s/XRV2m/ 看看这个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. 创建一个缓存来存储现有元素的id,这样每次要生成新ID时都不会产生性能开销。
  2. Auto Generate an incremental id based upon the tag name you pass to it. 自动根据传递给它的标记名称生成增量ID。
  3. Update the cache if you really plan on using the id's. 如果您真的打算使用id,请更新缓存。

I am just printing the id's on the console for convenience. 为方便起见,我只是在控制台上打印id。

Just my 2 cents based on some of your earlier comments to other's replies. 根据您之前对其他人的回复的一些评论,我只需要2美分。

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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM