3

How to efficiently assign a variable depth nested object only with a value and a string of type:

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

To get:

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

4 Answers 4

2

You can also use reduce() method.

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))

Sign up to request clarification or add additional context in comments.

1 Comment

Smart answer ! Didn't think about reduce
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'));

Comments

0

I personnaly use Lodash for that kind of things.

https://lodash.com/docs/#set does what you are looking for.

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

3 Comments

Well, you need an object for this. I use my solution to pass an arbitrary hash to Redux reducers through an action
I thought you already had an object. If you wish to create a new object, just write an empty object as the first arg: _.set({}, 'obj.source.name', 'myValue');
Nice solution !
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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.