gpt4 book ai didi

javascript - 使用数组值创建嵌套对象

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

我有一组键:

var keys = ['key1', 'key2', 'key3'];

如何以最简单的方式创建这样的对象?

var object = { 'key1' : { 'key2' : {'key3' : 'value' }}}

最佳答案

您可以利用 JavaScript 存储 Object 引用这一事实:

var keys = ['key1', 'key2', 'key3']; // input data
var object = {}; // output data
var current = object; // we will use this to recursively insert
// a new object

for(var i = 0; i < keys.length; i++) { // iterate through input data

if(i === keys.length - 1) {

current[keys[i]] = 'value'; // if it's the last element, insert 'value'
// instead of a new object

} else {

current[keys[i]] = {}; // otherwise insert a new element in the
// current object with key of 'key1' etc
// (from input data)

current = current[keys[i]]; // set current object to this one, so that
// next time it will insert an object into
// this newly created one

}

}

关于javascript - 使用数组值创建嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6439671/

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