从字符串创建JavaScript对象

时间:2015-08-15 21:30:08

标签: javascript object dom

我试图创建一个JavaScript函数,该函数使用结构的字符串创建一个对象,并从DOM数据中填充它。

例如,以下字符串可能如下所示:

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

应创建此对象:

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

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

这是函数的代码:

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;
}

有谁知道该怎么做?

3 个答案:

答案 0 :(得分:4)

我会这样做:

var createObject = function(model, name, value) {
  var nameParts = name.split("."),
  currentObject = model;
  for (var i in nameParts) {
    var part = nameParts[i];
    if (i == nameParts.length-1) {
      currentObject[part] = value;
      break;
    }
    if (typeof currentObject[part] == "undefined") {
      currentObject[part] = {};
    }
    currentObject = currentObject[part];
  }
};

然后像这样使用它:

var model = {};
createObject(model, "some.example.here", "hello");
createObject(model, "some.example.there", "hi");
createObject(model, "other.example", "heyo");

答案 1 :(得分:2)

这可能适合你(根据我的另一个项目改编,根据需要调整和使用): 请注意,元素的name被视为keyvalue被视为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);

上面的示例元素将提供以下model

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

答案 2 :(得分:0)

一些功能实现:

'foo.bar.baz'.split('.').reverse().reduce((reduction, segment, index) => {
  const result = {};
  if (index === 0) {                                                                 
    result[segment] = currentTarget.value;
  } else {                                                               
    result[segment] = reduction;
  }

  return result;
}, {})