用点表示法创建对象

用点表示法创建对象

本文介绍了用点表示法创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对.

给出一个对象x={a:1,b:2}和一个字符串c.d=3,将对象x修改为以下内容:

Given an object x={a:1,b:2} and a string c.d=3, modify object x to the following:

{
  a:1,
  b:2,
  c:{
    d:3
  }
}

我正在寻找不使用eval的解决方案.用例如下:

I'm looking for a solution that does not use eval. The use case is as follows:

x是一个配置对象,我们称之为:config.set("music.shuffle",true)

x being a configuration object, we call:config.set("music.shuffle",true)

现在,必须以某种方式解析music.shuffle并将其添加到config.set函数内部的内部对象x中,以便x看起来像:

Now, music.shuffle must be parsed somehow and added to the internal object x inside the config.set function, so that x looks something like:

x={a:1,b:2,music:{shuffle:true}}

推荐答案

我想您可以执行以下操作:

Off the top of my head I guess you can do something like this:

function addValueToObj(obj, newProp) {
    newProp = newProp.split("=");       // separate the "path" from the "value"

    var path = newProp[0].split("."),     // separate each step in the "path"
        val = newProp.slice(1).join("="); // allow for "=" in "value"

    for (var i = 0, tmp = obj; i < path.length - 1; i++) {
       tmp = tmp[path[i]] = {};     // loop through each part of the path adding to obj
    }
    tmp[path[i]] = val;             // at the end of the chain add the value in
}

var x = {a:1, b:2};
addValueToObj(x, "c.d=3");
// x is now {"a":1,"b":2,"c":{"d":"3"}}
addValueToObj(x, "e.f.g.h=9=9");
// x is now {"a":1,"b":2,"c":{"d":"3"},"e":{"f":{"g":{"h":"9=9"}}}}

演示: http://jsfiddle.net/E8dMF/1/

这篇关于用点表示法创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:03