从字符串创建JavaScript对象 [英] Create a JavaScript object from string

查看:75
本文介绍了从字符串创建JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个JavaScript函数,该函数使用字符串作为结构来创建对象并从DOM数据中填充它。

I'm trying to create a JavaScript function that creates an object using strings for structure and fills it from DOM data.

例如,以下字符串可能看起来像这样:

For example, the following strings could look like this:

some.example.here = "hello"
some.example.there = "hi"
other.example = "heyo"

应创建该对象:

{
    some: {
        example: {
            here: "hello",
            there: "hi"
        },
    other: {
        example: "heyo
    }
}

上述数据来自DOM,并正在标记为将数据读入对象的代码段中加载。数据加载正常,对象结构也正常设置,但没有将数据放入数据字段。

The data as said comes from DOM and is being load at the code segment labeled "read data into object". The data loads fine and the object structure is being setup fine as well, but the data is not being put into the data field.

以下是该函数的代码:

function getDataFromElement(element) {
  obj = {};
  $(element)
    .find("[data-value]")
    .each(function() {
      // create object node
      valueObj = {};
      currentValueObj = valueObj;
      $.each($(this).attr("data-value").split("."), function(i, objpath) {
        currentValueObj[objpath] = {};
        currentValueObj = currentValueObj[objpath];
      });

      // read data into object
      if($(this).is("[data-putvalue]") && $(this).attr("data-putvalue") != "html") {
        currentValueObj = $(this).attr($(this).attr("data-putvalue"));
      } else {
        currentValueObj = $(this).html();
      }

      console.log(currentValueObj);

      // combine with previous gathered data
      obj = $.extend(true, {}, obj, valueObj);
    });

  return obj;
}

有人知道该怎么做吗?

推荐答案

这可能适合您(改编自我的另一个项目,根据需要进行调整和使用):
注意元素的名称被当作,而 value 被当作 value

Probably this can suit you (adapted from another project of mine, adapt and use as needed): NOTE the element's name is taken as key and value as the value

function fields2model( $elements, dataModel )
{
    $elements.each(function( ){
        var $el = $(this), 
            name = $el.attr('name'), 
            key, k, i, o, val
        ;

        key = name;

        val = $el.val() || '';

        k = key.split('.'); o = dataModel;
        while ( k.length )
        {
            i = k.shift( );
            if ( k.length ) 
            {
                if ( !o.hasOwnProperty( i ) ) o[ i ] = /^\d+$/.test( k[0] ) ? [ ] : { };
                o = o[ i ];
            }
            else 
            {
                o[ i ] = val;
            }
        }
    });
}

示例用法:

<input name="some.example.here" value="hello" />
<input name="some.example.there" value="hi" />


var model = {};
fields2model($('input,textarea,select'), model);

上面的示例元素将给出下面的模型

The example elements above will give the below model:

model = {
some: {
    example: {
        here: "hello",
        there: "hi"
    }
};

这篇关于从字符串创建JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆