【问题标题】:Create a JavaScript object from string从字符串创建一个 JavaScript 对象
【发布时间】:2015-08-15 21:30:08
【问题描述】:

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

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

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

应该创建这个对象:

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

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

这是函数的代码:

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

有人知道该怎么做吗?

【问题讨论】:

  • 可以在问题中包含html 吗? , 创建 stacksn-ps , jsfiddle jsfiddle.net 演示?
  • currentValueObj = currentValueObj[objpath]; 的目的是什么?
  • 在第二个 each 循环中,我试图创建对象结构,因此循环遍历字符串的每个元素,创建一个具有当前字符串元素名称的新子元素 currentValueObj[objpath] = {};并使用currentValueObj = currentValueObj[objpath]; 进入该子元素,以便在下一个循环遍历中创建下一个子元素。
  • currentValueObj 在每次迭代时都会被覆盖?可以在 Question 中包含html,创建stacksn-ps来演示吗?

标签: javascript object dom


【解决方案1】:

我会这样做:

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

【讨论】:

  • 这会为每个键值创建不同的模型/对象
【解决方案2】:

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

【讨论】:

【解决方案3】:

一些功能实现:

const value = 'hello';
'some.example.here'.split('.').reverse().reduce((reduction, segment, index) => {
  const result = {};
  if (index === 0) {                                                                 
    result[segment] = value;
  } else {                                                               
    result[segment] = reduction;
  }

  return result;
}, {})

【讨论】:

  • currentTarget 来自哪里?
【解决方案4】:

@theFreedomBanana +1

为我工作

const magicFunction = (string, value) =>
  string
    .split('.')
    .reverse()
    .reduce((acc, cur, index) => ({ [cur]: index === 0 ? value : acc }), {});

【讨论】:

  • 请不要添加“谢谢”作为答案。相反,只需对您认为有帮助的答案进行投票即可。 - From Review
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
  • 2015-10-14
  • 2015-01-23
  • 1970-01-01
  • 1970-01-01
  • 2018-09-07
  • 1970-01-01
相关资源
最近更新 更多