我需要从数组值创建对象属性并为其指定一些值,例如
var main_obj = {};
var dynamic_array = ["value1", "value2", "value3", "value4"];
从dynamic_array
我需要创建main_obj
,如:
main_obj[value1][value2][value3] = some_value;
请给我一些建议。
答案 0 :(得分:0)
dynamic_array.forEach(function(prop){
main_obj[prop] = some_value;
});
答案 1 :(得分:0)
尝试解释您的问题,这可能是您正在寻找的解决方案:
function createNestedProperties(obj, array, value) {
var result = {};
var result_tmp = obj;
var i = 0;
while (i < array.length) {
if (i < (array.length - 1))
result_tmp[array[i]] = {};
else
result_tmp[array[i]] = value;
result_tmp = result_tmp[array[i]];
i++;
}
return obj;
}
以这种方式使用:
var main_obj = {"value1":{"value2":{"value3":{}}}};
var dynamic_array = ["value1", "value2", "value3"];
main_obj = createNestedProperties(main_obj, dynamic_array, {"value_Z":"new value"});
结果对象:
{"value1":{"value2":{"value3":{"value_Z":"new value"}}}}
如果已经存在,此函数将覆盖main_obj
中的现有属性。
答案 2 :(得分:0)
这是另一种方式
var dynamic_array = ["value1","value2","value3"];
var value = 'your value';
function createobj(dynamic_array,value){
var count = dynamic_array.length;
var text= '';
var ended = '';
for(var i = 0; i < count; i++){
text += '{"'+dynamic_array[i]+'":';
ended +='}';
}
text += '"'+value+'"'+ended;
return JSON.parse(text);
}
console.log(createobj(dynamic_array,value));
答案 3 :(得分:0)
我递归地解析对象,而不是构建jQuery - How to recursively loop over an object's nested properties?
function recursiveIteration(main_obj) {
for (var property in main_obj) {
if (property == value3)
{
main_obj[property] = {"value4":test};
}
else
{
recursiveIteration(main_obj[property]);
}
}
}
recursiveIteration(main_obj);