我需要使用存储在数组中的值创建一个 JavaScript 对象。每个值都应该是前一个值中的新键。实现这一目标的最佳方法是什么?
var option = ['level_1','level_2','level_3','level_4'];
$.each( option, function( key, value ) {
// ....
});
// I'm trying to get this result
var result = {
'level_1': {
'level_2': {
'level_3': {
'level_4':{}
}
}
}
}
最佳答案
您可以使用reduceRight
为此,使用 ES6 computed property name语法。
const option = ['level_1','level_2','level_3','level_4'];
const obj = option.reduceRight( (acc, lvl) => ({ [lvl]: acc }), {});
console.log(obj);
在传统的函数语法中,它是:
const obj = option.reduceRight(function (acc, lvl) {
return { [lvl]: acc };
}, {});
关于javascript - 使用 jquery .each 循环从数组中的值创建多维 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48451569/