在数组中指定级别时转换对象列表 [英] Convert list of Objects when the levels are given in an array
本文介绍了在数组中指定级别时转换对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个数组,该数组告诉我标签列表以及将它们添加到JSON对象中所需的值.您如何改变它?
Suppose I have an array which tells me the list of labels and a value that I need to add them into a JSON object. How do you transform it so?
所以基本上我有一个数组和一个值100
So basically I have is an array and a value 100
arr = ["1", "Male"]
应该这样将其转换为对象.
Should be transform it into a object as so.
obj = {
"1":{
"Male":100
}
}
推荐答案
You could use reduceRight
for this. Use value
as the initialValue
of reduce and create a new level of nesting in every loop.
function createObj(paths, value) {
return paths.reduceRight((r, key) => ({ [key] : r }), value)
}
console.log(createObj(["1", "Male"], 100))
console.log(createObj(["level 1", "level 2", "level 3" ], "value"))
这篇关于在数组中指定级别时转换对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文