Javascript:如何使用数组给定的对象名称动态创建嵌套对象 [英] Javascript: how to dynamically create nested objects using object names given by an array

查看:36
本文介绍了Javascript:如何使用数组给定的对象名称动态创建嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人可以帮助我使用这个 Javascript.

I hope someone can help me with this Javascript.

我有一个名为设置"的对象,我想编写一个函数来向该对象添加新设置.

I have an Object called "Settings" and I would like to write a function that adds new settings to that object.

新设置的名称和值以字符串形式提供.给出设置名称的字符串然后被下划线分割成一个数组.新的设置应该通过创建新的嵌套对象添加到现有的设置"对象中,该对象的名称由数组的每个部分给出,除了最后一部分应该是给出设置值的字符串.然后我应该能够参考设置,例如提醒它的价值.我可以像这样以静态方式做到这一点...

The new setting's name and value are provided as strings. The string giving the setting's name is then split by the underscores into an array. The new setting should get added to the existing "Settings" object by creating new nested objects with the names given by each part of the array, except the last part which should be a string giving the setting's value. I should then be able to refer to the setting and e.g. alert its value. I can do this in a static way like this...

var Settings = {};
var newSettingName = "Modules_Video_Plugin";
var newSettingValue = "JWPlayer";
var newSettingNameArray = newSettingName.split("_");

Settings[newSettingNameArray[0]] = {};
Settings[newSettingNameArray[0]][newSettingNameArray[1]] = {};
Settings[newSettingNameArray[0]][newSettingNameArray[1]][newSettingNameArray[2]] = newSettingValue;

alert(Settings.Modules.Mediaplayers.Video.Plugin);

...创建嵌套对象的部分正在执行此操作...

... the part that creates the nested objects is doing this ...

Settings["Modules"] = {};
Settings["Modules"]["Video"] = {};
Settings["Modules"]["Video"]["Plugin"] = "JWPlayer";

但是,由于构成设置名称的部分数量可能会有所不同,例如newSettingName 可以是Modules_Floorplan_Image_Src",我想使用诸如...之类的函数动态执行此操作

However, as the number of parts that make up the setting name can vary, e.g. a newSettingName could be "Modules_Floorplan_Image_Src", I'd like to do this dynamically using a function such as...

createSetting (newSettingNameArray, newSettingValue);

function createSetting(setting, value) {
    // code to create new setting goes here
}

谁能帮我弄清楚如何动态地做到这一点?

Can anyone help me work out how to do this dynamically?

我认为必须有一个 for... 循环来遍历数组,但我无法找到一种方法来创建嵌套对象.

I presume there has to be a for...loop in there to itterate through the array, but I haven't been able to work out a way to create the nested objects.

如果你读到这里,非常感谢你花时间阅读,即使你无能为力.

If you've got this far thanks very much for taking the time to read even if you can't help.

推荐答案

function assign(obj, keyPath, value) {
   lastKeyIndex = keyPath.length-1;
   for (var i = 0; i < lastKeyIndex; ++ i) {
     key = keyPath[i];
     if (!(key in obj)){
       obj[key] = {}
     }
     obj = obj[key];
   }
   obj[keyPath[lastKeyIndex]] = value;
}

用法:

var settings = {};
assign(settings, ['Modules', 'Video', 'Plugin'], 'JWPlayer');

这篇关于Javascript:如何使用数组给定的对象名称动态创建嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆