我想生成一个动态对象并为其赋值。以下是代码
var chunk = "INTERNATIONALISATION#LANGUAGE#DICTIONARY#EN";
var c = chunk.split('#');
var a = {};
所以输出应该是这样的
a["INTERNATIONALISATION"]["LANGUAGE"]["DICTIONARY"]["EN"] = 10;
尝试循环遍历数组,但现在没有任何作用。请告知。
答案 0 :(得分:7)
试试这个:
var chunk = "INTERNATIONALISATION#LANGUAGE#DICTIONARY#EN";
var c = chunk.split('#');
var a = {};
var lastKey = c.pop();
c.reduce((obj, key) => obj[key] = {}, a)[lastKey] = 10;