我将尝试创建一个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;
}
有人知道该怎么做吗?
currentValueObj = currentValueObj[objpath];
的目的是什么? - guest271314currentValueObj[objpath] = {};
进入该子元素,以便在下一个循环中创建下一个子元素。 - Lukas BachcurrentValueObj
在每次迭代中都被覆盖了吗?问题中可以包含html
,创建 stacksnippets 来演示吗? - guest271314