我正在嘗試創建一個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];'進入該子元素,以便在下一個循環遍歷中創建下一個子元素。 –