-1

I would like to achieve something like this:

let database = {
  foo: {
    bar: {}
  }
}

deepValue(database, "foo/bar/hello") = "world"

console.log(database)
// database: {
//   foo: {
//     bar: {
//       hello: "world"
//     }
//   }
// }

So deepValue returns the place in an object with the given path, so I can write to it. Is there something maybe in ES6, ES7 that could help me with this issue? Or is there a good way to generate the object path from a string?

Answered:

Ack, got closed before I could post. Here: jsfiddle.net/6bb1Lq6k – Jamiec

Balázs Orbán
  • 559
  • 1
  • 4
  • 26

1 Answers1

-2

This example provides a basic solution to the above problem. It breaks it down to the core. The solution, however possible is horrible and should be regarded as a proof of concept and there a many way to breaks this. There are far better ways to maintain your code. Please see the duplicate entry which covers this way beter: Convert JavaScript string in dot notation into an object reference

Array based

let database = {
  foo: {
    bar: {}
  }
}

//changed assignment to argument, since this will fail with invalid left hand assignment.
deepValue(database, "foo/bar/hello", "world");

function deepValue(dbase, stringValue, val)
{
var obj = dbase; //start the chain at base object

//split the string based upon the slashes.
//loop the array with forEach 
stringValue.split("/").forEach(function(value, index, arr){
  
  //if searched value does not exist, create
  if (!obj[value])
  {
    obj[value] = {}; //we use bracket notation, eliminating the need for eval.
  }
  obj = obj[value]; //assign the current property as newest in the chain.
  if (index == arr.length-1 && val)
  {
     obj[value] = val; //if object reaches the end of the chain and there is a val set, assign it. We check the index against the array's length.
  }
}); //array from split

}

console.log(database)
Mouser
  • 13,132
  • 3
  • 28
  • 54