I am trying to create a JavaScript function that creates an object using strings for a structure and populates it from DOM data.
For example, the following lines might look like this:
some.example.here = "hello"
some.example.there = "hi"
other.example = "heyo"
Which should create this object:
{
some: {
example: {
here: "hello",
there: "hi"
},
other: {
example: "heyo
}
}
The data, as said, comes from the DOM and is loaded into the code segment with the inscription "reading data into an object." The data loads fine, and the structure of the object is also fine tuned, but the data does not fit into the data field.
Here's the function code:
function getDataFromElement(element) {
obj = {};
$(element)
.find("[data-value]")
.each(function() {
valueObj = {};
currentValueObj = valueObj;
$.each($(this).attr("data-value").split("."), function(i, objpath) {
currentValueObj[objpath] = {};
currentValueObj = currentValueObj[objpath];
});
if($(this).is("[data-putvalue]") && $(this).attr("data-putvalue") != "html") {
currentValueObj = $(this).attr($(this).attr("data-putvalue"));
} else {
currentValueObj = $(this).html();
}
console.log(currentValueObj);
obj = $.extend(true, {}, obj, valueObj);
});
return obj;
}
Does anyone know what to do?
source
share