我有一组键:
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/