用点表示法创建一个对象

问题描述 投票:5回答:7

这是对this question的反向问题。

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

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

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

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

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

x={a:1,b:2,music:{shuffle:true}}
javascript json
7个回答
10
投票

在我的脑海中,我猜你可以这样做:

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"}}}}

但是:ぁzxswい


4
投票

我相信dojo的setObject可以满足您的需求。如果你(可以理解)不想提取所有dojo,那么我建议通过AMD检查他们的(免费提供)源或加载基础(仅4k)。它看起来像这样:

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

所以在你的情况下你会这样做:

function setObject(name, value, context) {
    var parts=name.split("."), 
    p=parts.pop();
    for(var i=0, j; context && (j=parts[i]); i++){
        context = (j in context ? context[j] : context[j]={});
    }
    return context && p ? (context[p]=value) : undefined; // Object
}

警告:除非您只处理琐碎的案例,否则我会敦促您查看完整的dojo实现,该实现处理没有提供上下文等的情况。


4
投票

你可以用x={a:1,b:2}; setObject("c.d", 3, x); 做到这一点

> l=require('lodash')
> x={a:1,b:2};
{ a: 1, b: 2 }
> l.set(x, 'c.d', 3)
{ a: 1, b: 2, c: { d: 3 } }

2
投票

这是一个评论很多的版本,应该有点简单易懂。

lodash.set()

2
投票

今天必须做类似的事情,这是另一个解决方案。绝对可以使用一些清理工作,但它可以解决问题。这将扩展现有对象,并且在输入有效的情况下不会擦除任何数据。

没有验证,因此如果您传递错误数据,您肯定可以覆盖密钥。

// stores the configured data
configStore = {};

config = {
  set: function(keyValueString) {

    // Split the string by the =
    var pair = keyValueString.split('=');

    // left of the = is the key path
    var keyPath = pair[0];

    // right of the = is the value to set
    var value = pair[1];

    // split keyPath into an array of keys
    var keys = keyPath.split('.');
    var key; // used in loop

    // the current level of object we are drilling into.
    // Starts as the main root config object.
    var currentObj = configStore;

    // Loop through all keys in the key path, except the last one (note the -1).
    // This creates the object structure implied by the key path.
    // We want to do something different on the last iteration.
    for (var i=0; i < keys.length-1; i++) {

      // Get the current key we are looping
      key = keys[i];

      // If the requested level on the current object doesn't exist,
      // make a blank object.
      if (typeof currentObj[key] === 'undefined') {
        currentObj[key] = {};
      }

      // Set the current object to the next level of the keypath,
      // allowing us to drill in.
      currentObj = currentObj[key];
    }

    // Our loop doesn't handle the last key, because that's when we
    // want to set the actual value. So find the last key in the path.
    var lastKey = keys[keys.length-1]

    // Set the property of the deepest object to the value.
    currentObj[lastKey] = value;
  }
};

// Do it.
config.set('omg.wtf.bbq=123')

// Check it.
alert(configStore.omg.wtf.bbq); // 123

功能原型可以改进,但满足我的需求。通过以下方式呼叫

// @param object orig    the object to extend
// @param array keyParts the.key.path split by "." (expects an array, presplit)
// @param mixed value    the value to assign
// @param object scoped  used by the recursion, ignore or pass null
function unflatten(orig, keyParts, value, scoped) {
    if (!scoped) {
        scoped = orig;
    }

    var nextKey = keyParts.shift();

    if (keyParts.length === 0) {
        scoped[nextKey] = value;
        return orig;
    }

    if (!scoped[nextKey]) {
        scoped[nextKey] = {};
    }

    scoped = scoped[nextKey];
    return unflatten(orig, keyParts, value, scoped);
}

0
投票

这个怎么样?

它将创建或复制/覆盖现有对象。

var orig = { foo: 'hello world', bar: { baz: 'goodbye world' } };

// lets add the key "bar.cat.aww" with value "meow"
unflatten(orig, "bar.cat.aww".split("."), "meow");
/* 
  orig is { 
    foo: "hello world", 
    bar: { 
      baz: "goodbye world", 
      cat: { 
        aww: "meow" 
      } 
    } 
  }

*/

// we can keep calling it to add more keys
unflatten(orig, "some.nested.key".split("."), "weeee");

/* 
  orig is { 
    foo: "hello world", 
    bar: { 
      baz: "goodbye world", 
      cat: { 
        aww: "meow" 
      } 
    },
    some: {
      nested: {
        key: "weeee"
      }
    }
  }
*/

注意:箭头功能和function expando(obj, base) { return Object.keys(obj) .reduce((clone, key) => { key.split('.').reduce((innerObj, innerKey, i, arr) => innerObj[innerKey] = (i+1 === arr.length) ? obj[key] : innerObj[innerKey] || {}, clone) return clone; }, Object.assign({}, base)); } console.log(expando({'a.b': 1})) // { a: { b : 1 }} console.log(expando({'b.c': 2}, { a: 1 })) // { a: 1, b: { c: 2 }} console.log(expando({'b.c.d': 2, 'e.f': 3}, { a: 1 })) // { a: 1, b: { c: { d: 2 } }, e: { f: 3}} 需要ES6。

随意玩耍:

Object.assign()


0
投票

那这个呢 :

https://jsbin.com/setazahuce/1/edit?js,console

使用输入对象的示例(可能是使用$ .serializeArray提取的某些表单值)

function setObj (str, value, obj) {
    var ref = obj, keys = str.split('.');
    while (keys.length) {
        var currentKey = keys.shift();
        ref[currentKey] = keys.length ? (ref[currentKey]  ? ref[currentKey] : {}) : value;
        ref = ref[currentKey];
    }
}

结果

var serializedInputs = [
    {name: 'fruits[1][name]', value: 'Banana'},
    {name: 'fruits[1][id]', value: '1'},
    {name: 'fruits[2][name]', value: 'Strawberry'},
    {name: 'fruits[2][id]', value: '2'},
    {name: 'fruits[3][name]', value: 'Raspberry'},
    {name: 'fruits[3][id]', value: '3'},
    {name: 'fruits[4][name]', value: 'Kiwi'},
    {name: 'fruits[4][id]', value: '4'},
    {name: 'fruits[5][name]', value: 'Mango'},
    {name: 'fruits[5][id]', value: '5'},
    {name: 'selected_fruit_id', value: '1'},
]
// This variable holds the result
var obj = {}
serializedInputs.forEach(function(item) {
    // Turning square brackets into dot notation
    setObj(item.name.replace(/\]/g, '').replace(/\[/g, '.'), item.value, obj);
})
© www.soinside.com 2019 - 2024. All rights reserved.