Create a JavaScript object from string

别等时光非礼了梦想. 提交于 2020-01-14 13:54:11

问题


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"

Which should create this object:

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

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.

Here's the code for the function:

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

Does anyone know what to do?


回答1:


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

Example use:

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



回答2:


I would do it like this:

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

And then use it like that:

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


来源:https://stackoverflow.com/questions/32029546/create-a-javascript-object-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!