我正在尝试创建一个JavaScript函数,该函数使用字符串为结构创建一个对象,并从DOM数据中填充它。从字符串创建一个JavaScript对象
例如,以下字符串可能看起来像这样:
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'? ,创建stacksnippets,jsfiddle http://jsfiddle.net来演示? – guest271314
'currentValueObj = currentValueObj [objpath]'的用途是什么;'? – guest271314
随着第二个循环,我试图创建对象结构,所以循环遍历字符串的每个元素,用currentValueObj [objpath] = {};创建一个带有当前字符串元素名称的新子元素;并通过'currentValueObj = currentValueObj [objpath];'进入该子元素,以便在下一个循环遍历中创建下一个子元素。 –