Javascript对象键值编码。动态设置嵌套值 [英] Javascript object key value coding. Dynamically setting a nested value

查看:217
本文介绍了Javascript对象键值编码。动态设置嵌套值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个小库,可以让我用对象做一些基本的键值编码。假设我有以下对象:

I'm working on a little library that lets me do some basic key value coding with objects. Say I have the following object:

var data = { key1: "value1", key2: { nested1: 1, nested2: "wowza!" } };

我有以下JavaScript功能:

And I have the following JavaScript function:

var setData = function(path, value) {
    eval("data." + path + "= value;");
};

并且在使用中:

setData("key1", "updated value1"); // data.key1 == "updated value1"
setData("key2.nested1", 99); // data.key2.nested1 == 99

这有效,但是我想完成上述工作不使用 eval 。这是可能的,还是 eval 最好的方法?

This works, however I would like to accomplish the above without using eval. Is this possible, or is eval the best way to go?

编辑:

注意可以假设您设置的值存在,至少对于路径深度 - 1.我更关心设置现有对象的值。

NOTE it can be assumed the value you're setting exists, at least for path depth - 1. I'm more concerned about setting the value of an existing object.

推荐答案

递归就是你需要的:

function setData(key,val,obj) {
  if (!obj) obj = data; //outside (non-recursive) call, use "data" as our base object
  var ka = key.split(/\./); //split the key by the dots
  if (ka.length < 2) { 
    obj[ka[0]] = val; //only one part (no dots) in key, just set value
  } else {
    if (!obj[ka[0]]) obj[ka[0]] = {}; //create our "new" base obj if it doesn't exist
    obj = obj[ka.shift()]; //remove the new "base" obj from string array, and hold actual object for recursive call
    setData(ka.join("."),val,obj); //join the remaining parts back up with dots, and recursively set data on our new "base" obj
  }    
}

setData("key1", "updated value1"); // data.key1 == "updated value1"
setData("key2.nested1", 99); // data.key2.nested1 == 99

这篇关于Javascript对象键值编码。动态设置嵌套值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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