gpt4 book ai didi

javascript - 如何从键字符串构建嵌套属性

转载 作者:行者123 更新时间:2023-11-28 02:09:49 26 4
gpt4 key购买 nike

var keys1 = ["foo", "moreFoo"],
value1 = "bar",
keys2 = ["foo", "ultraFoo"],
value2 = "bigBar";

我想创建一个函数来构建一个对象:

object {
foo : {moreFoo: "bar", ultraFoo: "bigBar"}
}

我想采用我的每个数组并执行以下操作:

function recursiveObjectBuild(object, keys, value) {
var index = 0;
function loop(object, index) {
var key = keys[index];
//Property exists, go into it
if (key in object) {
loop(object[key], ++index);
//Property doesn't exist, create it and go into it
} else if (index < keys.length-1) {
object[key] = {};
loop(object[key], ++index);
//At last key, set value
} else {
object[key] = value;
return object;
}
}
return loop(object, 0);
}

在我看来,这应该可以工作,但不能(无限循环,一定是一个愚蠢的错误,但看不到它)。

我确信一定有一种更简单的方法

最佳答案

尝试以下操作:

function objectBuild(object, keys, value) {
for (var i = 0; i < keys.length-1; i++) {
if (!object.hasOwnProperty(keys[i]))
object[keys[i]] = {};
object = object[keys[i]];
}
object[keys[keys.length-1]] = value;
}

用法示例(see it in action):

var object = {};
objectBuild(object, ["foo", "moreFoo"], "bar");
objectBuild(object, ["foo", "ultraFoo"], "bigBar");
// object --> {foo: {moreFoo: "bar", ultraFoo: "bigBar}}

关于javascript - 如何从键字符串构建嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17280096/

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