从字符串创建JavaScript对象

编程入门 行业动态 更新时间:2024-10-26 23:30:24
本文介绍了从字符串创建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对象

本文发布于:2023-10-28 02:05:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535184.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   对象   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!