gpt4 book ai didi

javascript - 从数据集值更新多级对象值

转载 作者:行者123 更新时间:2023-12-01 03:01:47 25 4
gpt4 key购买 nike

很难解释。

var options = {
container: node,
pin: {
size: [50, 50],
anchor: 0,
animation: 0
}
}

我们以上面的Object为例。我想从 HTMLElement 循环访问数据集并使用数据集值更新上述值。这样就无需手动检查数据集值是否存在然后替换该值。

到目前为止我得到了什么:

(function() {
for( const data in node.dataset ) {
// First remove the 'map' as this isn't required, then split any values with multiple capitals,
// as these corrospond to multilevel object values.
var key = (data.replace("map", "")).split(/(?=[A-Z])/), value = node.dataset[data];

const findOption = function() {

};

// Check that there is a value
if (value !== null) {
const opt = null;
// Find the corresponding default option

}
}
}.call(_));

这是带有数据集属性的 HTML,这应该有助于一切变得更有意义:

<div data-map data-map-offset='[10, 10]' data-map-pin-size='[20, 20]'></div>

正如您在上面看到的,属性 data-map-pin-size 需要替换对象内的值,但我不确定如何像通常那样引用该对象options.pin.sizeoptions['pin']['size']。但由于这个循环不知道它需要多深,我不能总是依赖它,我需要某种回调函数,对吗?这就是为什么我开始 findOption() 但我不太确定从那里去哪里!

编辑:这是我到目前为止所得到的,但这并没有更新 options 对象,它只是设置 opt 的值。

(function() {
for( const data in node.dataset ) {
// First remove the 'map' as this isn't required, then split any values with multiple capitals,
// as these corrospond to multilevel object values.
var key = (data.replace("map", "")).split(/(?=[A-Z])/), value = node.dataset[data];
// Pin Size
const findOption = function(val) {
return options[val.toLowerCase()];
};
// Check that there is a value
if (value !== null) {
var opt = null;
// Find the corresponding default option
for (var x = 0; key.length > x; x++) {
opt = findOption(key[x]);
}
opt = value;
}
}
console.log(options);
}.call(_));

最佳答案

如果您将选项转换为以下格式:

var options = {
container: node,
pinSize: [50, 50],
pinAnchor: 0,
pinAnimation: 0
}

您的实现可以简化为:

for (const key in node.dataset) {
const opt = key.replace(/^map(.)/, (match, c) => c.toLowerCase())
options[opt] = JSON.parse(node.dataset[key])
}

假设您打算在 HTML data- 属性中使用符合 JSON 的值。

关于javascript - 从数据集值更新多级对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46403635/

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