动态引用嵌套的Javascript对象 [英] Referencing a Nested Javascript Object dynamically

查看:108
本文介绍了动态引用嵌套的Javascript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组( $ scope.fields ),用于定义如何为 $ scope.data <设置输入字段/ code>对象模型。 fieldName属性实际上是该字段的 data 对象中的路径。嵌套对象由句点标记分隔。

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.

例如:

    $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}
    ]

HTML中绑定$ scope.data字段的最佳方法是什么? fieldName。我知道javascript eval - 但这是最​​好的方法吗?为什么这种语法对我不起作用?

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>


推荐答案

最近我开发了一种Object方法来完成这项工作。这种单线性递归方法动态访问数组对象结构中的任何值,无论它的嵌套程度如何。根据您的示例

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

这篇关于动态引用嵌套的Javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆