Javascript按数组创建对象 [英] Javascript create Object by array
问题描述
我尝试使用最后一个键的值创建一个对象.我只有一个带有键和值的数组,但不知道如何在 javascript 中不使用引用来创建对象.
I try to create an object with a value for the last key. I just have an Array with the keys and the value but dont know how it will be possible to create an object without use references in javascript.
据我所知,没有办法在 javascript 中创建变量的引用.
As far as I know there isnt a way to create a reference of a variable in javascript.
这就是我所拥有的:
var value = 'test';
var keys = ['this', 'is', 'a', 'test'];
这就是我想要的:
myObject: {
this : {
is: {
a : {
test : 'test'
}
}
}
}
知道如何在 JavaScript 中以最佳方式做到这一点吗?
Any idea how i can do this the best way in JavaScript ?
推荐答案
这个怎么样...
const value = 'test'
const keys = ['this', 'is', 'a', 'test']
const myObject = keys.reduceRight((p, c) => ({ [c]: p }), value)
console.info(myObject)
或者,如果您不喜欢对象文字快捷键和箭头函数...
Or, if you're not a fan of object literal key shortcuts and arrow functions...
keys.reduceRight(function(p, c) {
var o = {};
o[c] = p;
return o;
}, value);
参见 Array.prototype.reduceRight() - Polyfill 如果您需要 IE <= 8 支持.
See Array.prototype.reduceRight() - Polyfill if you need IE <= 8 support.
这篇关于Javascript按数组创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!