gpt4 book ai didi

javascript - 从字符串创建一个 JavaScript 对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:44:27 24 4
gpt4 key购买 nike

我正在尝试创建一个 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;
}

有人知道怎么办吗?

最佳答案

我会这样做:

var createObject = function(model, name, value) {
var nameParts = name.split("."),
currentObject = model;
for (var i in nameParts) {
var part = nameParts[i];
if (i == nameParts.length-1) {
currentObject[part] = value;
break;
}
if (typeof currentObject[part] == "undefined") {
currentObject[part] = {};
}
currentObject = currentObject[part];
}
};

然后像这样使用它:

var model = {};
createObject(model, "some.example.here", "hello");
createObject(model, "some.example.there", "hi");
createObject(model, "other.example", "heyo");

关于javascript - 从字符串创建一个 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32029546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com