Referencing a Nested Javascript Object dynamically
Asked Answered
N

2

0

I have an array of objects ($scope.fields) that define how input fields should be set up for the $scope.data object model. The fieldName property is actually the path in the data Object to the field. Nested objects are separated by a period mark.

eg:

    $scope.data = {
        user: {
        }
    }
    $scope.fields = [
        {fieldName:'user.firstName',fieldLabel:'First Name',dsiabled:false}
        {fieldName:'user.location.lat',fieldLabel:'Latitude',dsiabled:false}
        {fieldName:'user.location.long',fieldLabel:'Latitude',dsiabled:false}
    ]

What is the best way in the HTML to bind the $scope.data fields based on the fieldName. I am aware of javascript eval - but is that the best way to do it ? And why does this syntax not work for me ?

ie:

 <div ng-repeat="fieldObj in fields">
    <dd ng-bind="eval('data.' fieldObj.fieldName)"></dd>
 </div>
Nilson answered 4/6, 2015 at 18:36 Comment(2)
See Accessing nested JavaScript objects with string key... however I have no idea how that can be integrated with Angular. "why does this syntax not work for me" Presumably you cannot put arbitrary expressions in ng-bind.Mikiso
so technically i can ng-bind to a function that will return the correct binding - thanks for your help Felix King. I am going to test it now.Nilson
N
0

Thanks to @Felix Kling I worked out how to do it.

I used the Object by string idea from Felix_kings ref, and applied a callback function to the ng-bind that received the full object reference.

Nilson answered 4/6, 2015 at 19:35 Comment(0)
C
0

Recently i have developed an Object method to do this job. This single liner recursive approach dynamically accesses any value within an array object structure regardless how deeply nested it is. As per your example

var fields = [
  {fieldName:'user.firstName',fieldLabel:'First Name',dsiabled:false},
  {fieldName:'user.location.lat',fieldLabel:'Latitude',dsiabled:false},
  {fieldName:'user.location.long',fieldLabel:'Latitude',dsiabled:false}
];

Object.prototype.getNestedValue = function(...a) {
  return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};

document.write(fields.getNestedValue(0,"fieldName"));

For a moredeeply structured object you can always do like

Object.prototype.getNestedValue = function(...a) {
  return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};

var arr = [{fox: [{turn:[857, 432]}]}, {sax: [{pana:[777, 987]}]}, {ton: [{joni:[123, 567]}]}, {piu: [{burn:[666, 37]}]}, {sia: [{foxy:[404, 696]}]}],
  myObj = { foo : 1, bar: { baz : 2 }, bee : 3 };

document.write(arr.getNestedValue(3,"piu",0,"burn",1));
Cockiness answered 6/5, 2016 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.