使用 Javascript 或 jQuery 将数组字符串转换为对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11120388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:08:03  来源:igfitidea点击:

Convert Array-String to Object with Javascript or jQuery

javascriptjqueryobject

提问by TrySpace

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

我列出id了页面上的每个 DOM 元素:

 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 Arrayto an Object, like:

现在我想将 listy 转换Array为 an 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 Objectlike:

但这将使一切都变得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()将数组转换为对象

Which brings me to a similar, but different question:

这让我想到了一个类似但不同的问题:

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

将页面元素索引到 JSON 对象?还是每次都用jQuery选择器呢?

回答by Blazemonger

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

listy是一个字符串,而不是一个数组。将您的第一个代码块更改为:

 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. Instead of calling DOMJSONTHING.body.div.h1to get the value "home", you can already call $('document > body > div > h1').attr('id')and get the same result.

至于创建索引整个文档的对象:出于什么目的?当您可以直接解析 DOM 时,自己做这件事没什么好处——尤其是因为 jQuery 使它变得如此简单。DOMJSONTHING.body.div.h1您已经可以调用$('document > body > div > h1').attr('id')并获得相同的结果,而不是调用以获取值“home” 。

回答by Robert Koritnik

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

但是正如我在其他答案中的评论中读到的那样,这个对象结构在您的情况下可能不是最好的。你想要的是检查一个特定的 ID 是否已经存在。这个对象

{
    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 ifstatement:

因为这样可以通过在if语句中简单地检查使用此条件来轻松确定特定 ID :

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:

所有不存在的 ID 都不会满足此条件,所有存在的 ID 都将返回true. 但是要将您的 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. 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:

这将最大限度地加快您现有的 ID 搜索速度。只要您可以在 O(1) 中获取有关 ID 存在的信息,检查 ID 的唯一性可能不需要分层对象结构。上关联数组对象将为您提供这种超快速的可能性。并且当您使用新 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 (listyvariable). Beware and avoid if possible.

注意:我可以看到您的代码隐含了全局(listy变量)。小心并尽可能避免。

Performance testing

性能测试

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

正如@Blazemonger 所暗示的那样,这并不成立,我会说这种说法可能是正确的。这一切都归结为:

  • the number of elements with IDs you have
  • number of searches you'd like to do
  • 您拥有的带有 ID 的元素的数量
  • 您想要进行的搜索次数

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 testproves 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.

如果第一个在常规 HTML 页面中通常较低,其中 CSS 类比 ID 更频繁地使用,并且如果第二个足够大,那么这个性能测试证明关联数组可以比单独使用 jQuery 快一些。本次测试中使用的 HTML 是移动站点上 Stackoverflow 问题列表的副本(因此我从源代码中删除脚本的工作较少)。我特意举了一个真实世界网站内容的例子,而不是准备好的测试用例,可以故意制造一个或另一个解决方案。

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 会比我直接使用 jQuery 更快,因为它不需要启动关联数组准备并立即开始搜索。

回答by thecodeparadox

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

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

DEMO

演示

回答by Ryan

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.
  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.
  1. 创建一个缓存来存储现有元素的 id,这样您就不会在每次想要生成新 id 时获得性能开销。
  2. 根据您传递给它的标签名称自动生成增量 ID。
  3. 如果您真的打算使用 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 美分。

回答by muthu

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
)