-1

Let's say I have a string like 'user.data', and I want to create the data field of this object:

const obj = {
  user: {
    data: {}
  }
}

I am not able to do this normally (obj['user.data'] = {}) with this string because it will do this:

const obj = {
  user: {},
  'user.data': {}
}

And that is not what I am looking for.

How would I go about creating a property with an object when that is the last part of the string?

const str = 'user.hobbies';
const obj = { user: {} };
addInNestedProp(str, obj);
console.log(obj);
// => { user: { hobbies: {} } }
yaas
  • 144
  • 2
  • 7
  • Sorry, but I have absolutely no idea what you're "asking"... firstly because there doesn't appear to be a question here... and secondly because what you're saying simply doesn't make any sense to me. – freefaller Jul 03 '19 at 14:15
  • To have hello.world.there you need `hello = { world: { there: {} } }` – mplungjan Jul 03 '19 at 14:21
  • 1
    You probably need something similar to this: [Convert JavaScript string in dot notation into an object reference](https://stackoverflow.com/questions/6393943) – adiga Jul 03 '19 at 14:23
  • 1
    I was messing around with this. It's not finished yet, but perhaps it'll be usefull to you: https://pastebin.com/hhbjzrPS – icecub Jul 03 '19 at 14:28
  • This is no a duplicate. The OP is asking how to use a string with a certain pattern to mutate an existing object by adding properties/values represented in that string. – Randy Casburn Jul 03 '19 at 15:26

1 Answers1

0

Here is a solution that will allow you to take a string such as "user.hobbies", evaluate an object against that string, and add any properties to the object that are in the string, but not in the object.

Using your input string "user.hobbies" will produce:

 {
  "name": "me",
  "user": {
    "avatarURL": "longURL",
    "hobbies": {}
  }
}

You can also try this with "user.hobbies.sports.basketball" and it will produce the object hierarchy you expect.

The code is heavily documented:

const existing = { name: 'me', user: { avatarURL: 'longURL' }};
const addInHobbyString = 'user.hobbies';

const newObject = addInObject(addInHobbyString, existing);

console.log(newObject);

function addInObject(term, obj) {
  // make a clone of the object 
  let objCopy = JSON.parse(JSON.stringify(obj));
  // separate serach terms
  let terms = term.split('.');
  // set temp obj to first search term as object property
  // any modifications to temp will be seen in objCopy
  let temp = objCopy[`${terms[0]}`];
  // Find the last search term that exists as an object property
  let q = terms.reduce((acc, curr, idx) => (objCopy[`${curr}`]) ? null : idx, 0);
  // Do the work
  for (let i = 1; i <= q; i++) {
    // if property doesn't exist on object create it and set it to an empty object
    if (!temp[`${terms[i]}`]) {
      temp[`${terms[i]}`] = {};
      // Set the search depth in our temp object to the next depth
      temp = temp[`${terms[i]}`]
    }
  }
  return objCopy;
}
Randy Casburn
  • 13,840
  • 1
  • 16
  • 31