0

I have a JSON Object

{scope:{results:{...}}}

And I have a String named

"data.one.url"

Now I want to set the value inside the JSON Object. Normally I would do it like this:

scope.results.data.one.url = "hello";

But how to do it when I only have the string mentioned above?

Joe
  • 46,419
  • 33
  • 155
  • 245
Niko Lang
  • 847
  • 2
  • 9
  • 17
  • i don't understand what `to take the value inside the JSON Object what would be like` means.. – Tommaso Bertoni Mar 03 '15 at 10:20
  • Sorry I am german and ry this as best as I could. I try to make it clearer – Niko Lang Mar 03 '15 at 10:23
  • @dfsq I use angular but I dont think it is important here. Correct if I am wrong. – Niko Lang Mar 03 '15 at 10:26
  • Yes, it's very important, because with Angular you can solve this problem in **one line** of code, because it already provides tool for string parsing and context resolution in `$parse` service. – dfsq Mar 03 '15 at 10:27

3 Answers3

1

Here's the data structure:

myData = {scope:{results:{data:{one:{url:"The url"}}}}}

Define a base. Your string access path is relative to this:

var base = myData.scope.results;

And a function to access by a path:

function getIn(base, path) {
  var components = path.split(".");
  var current = base;
  for (var i = 0; i < components.length; i++) {
    current = current[components[i]];
  }

  return current;
}

And to use it:

getIn(base, "data.one.url")
>>> "The url"

Or relative to the root:

getIn(myData, "scope.results.data.one.url")
>>> "The url"

Of course more error handling is needed to make it robust to paths you don't expect.

Joe
  • 46,419
  • 33
  • 155
  • 245
1

The simplest and the most convenient way in this case (since you are using AngularJS) is to use $parse service:

var str = 'data.one.url';
var url = $parse('results.' + str)($scope); // "hello"

Demo: http://plnkr.co/edit/NYLvWc1gOA5X3glIM1gI?p=preview

Angular uses $parse service internally for exactly this sort of things. When you write in HTML {{someobj.prop.name}} the string someobj.prop.name is interpreted against $scope with the help of $parse service. It's very cool that you can use it yourself if you want. Just make sure to inject service into your controller.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • In my code its actually a directive. How to inject it into the controller? – Niko Lang Mar 03 '15 at 11:45
  • In case of directive: `.directive('myDirective', ['$parse', function($parse) { return { link: function() {}, controller: function() {} }; }])`. – dfsq Mar 03 '15 at 11:50
  • Check the example of directive with injected $parse service: http://plnkr.co/edit/XEsj78I5k49ira2cp1X4?p=info – dfsq Mar 03 '15 at 11:52
-2

how about this (if I get it well) ?

var myJSON = {scope:{results:{...}}}
myJSON["scope"]["results"]["url"] = data.one.url
myJSON = JSON.Stringify(myJSON);

then you would have this object as a JSON: "{scope:{results:{url{value}}}}"

Eagle1
  • 810
  • 2
  • 12
  • 30