如何在JS(ES6)中以点状格式获取带有字符串的嵌套对象

时间:2017-02-09 14:09:19

标签: javascript ecmascript-6

如何仅使用值和字符串类型:

有效地分配变量深度嵌套对象
const names = 'obj.source.name'
const value = 'myValue'

获得:

{ obj: { source: { name: 'myValue' } } }

4 个答案:

答案 0 :(得分:2)

您也可以使用reduce()方法。

const names = 'obj.source.name'
const value = 'myValue'

function nestObj(keys, val) {
  var o = {}, k = keys.split('.')
  return k.reduce((r, e, i) => r[e] || (r[e] = (k.length-1 != i) ? {} : val), o), o
}

console.log(JSON.stringify(nestObj(names, value), 0, 4))

答案 1 :(得分:1)

function nestObject(names, value) {
  if (names.length === 0) {
    return value;
  }
  return nestObject(names.splice(0, names.length - 1), { [names.splice(-1)]: value })
}

function nestedProps(name, value) {
  if (Array.isArray(name)) {
    return nestObject(name, value);
  } else {
    return nestObject(name.split('.'), value);
  }
};
console.log(nestedProps('obj.source.name', 'myValue'));

答案 2 :(得分:0)

我个人使用Lodash来做这类事情。

https://lodash.com/docs/#set可以满足您的需求。

_.set({}, 'obj.source.name', 'myValue');

答案 3 :(得分:0)



function getObject(path, value) {
  let obj = {}, // the result object (the one to return)
      _r = obj; // will serve as a reference to a depth

  let parts = path.split('.'), // split the path
      last = parts.pop(); // remove the last one and store it to be used later to store the value
  
  parts.forEach(p => { // for each part (depth) in the path
    _r[p] = {}; // assign an empty object to this depth
    _r = _r[p]; // store its reference to be used as the current depth
  });
  _r[last] = value; // set the value at the last depth
  
  return obj;
}


const names = 'obj.source.name';
const value = 'myValue';

console.log(getObject(names, value));