简体   繁体   中英

Getting object property in JavaScript

I have a object from a get request from an API like this:

var object = {
  "number": 0,
  "size": 9999,
  "totalPages": 0,
  "numberOfElements": 1,
  "totalElements": 1,
  "content": [{
    "id": 26,
    "name": "New York",
    "acronym": "SP",
    "country": {
      "id": 33,
      "name": "United States",
      "acronym": "US"
    }
  }]
}

If I want to get the country name, I need to do:

object.content[0].country.name or object["content"][0]["country"]["name"]

However I am trying to access trough a ng-repeat those properties that I pass in the controller in order to generalize my controller.

Inside the controller I have:

$scope.$parent.fields = ["acronym", "name", "country.name"];
$scope.columns = [
  {
    field: $scope.fields[0],
    "class": 'col-sm-1'
  }, {
    field: $scope.fields[1],
    "class": 'col-sm-5'
  }, {
    field: $scope.fields[2],
    "class": 'col-sm-3'
  }
];

And the HTML:

<tr ng-repeat="item in elements.content">
  <td ng-repeat="column in columns">{{ item[column.field] }}</td>
  <td id="op">
    <button class="btn btn-xs btn-success" ng-click="preview(item)">
      <i class="fa fa-eye"></i> View
    </button>
    <button class="btn btn-xs btn-primary" ng-click="update(item)">
      <i class="fa fa-pencil"></i> Edit
    </button>
    <button class="btn btn-xs btn-danger" ng-click="remove(item)">
      <i class="fa fa-trash"></i> Delete
    </button>
  </td>
</tr>

It only works for the properties from the content object, but not properties of objects inside content. What can I do?

Thank you in advance for your time and help!

You'll likely need to create a helper function that parses the string you're passing in as a key and returns the object's value because you can't access an object's child properties using a string:

var item = {
  property: {
    child: 'somevalue'
  }
}

// this will return undefined
item['property.child']

Luckily this nice function exists:

function getDescendantProp(obj, desc) {
  var arr = desc.split(".");
  while(arr.length && (obj = obj[arr.shift()]));
  return obj;
}

It takes an object and string, turns the string into an array and traverses the properties of your passed in object until it reaches the property you're searching for. It will work for any depth of object property.

if you take this function and put it on your controller's scope you can then call it with your field's name and item object:

<td ng-repeat="column in columns">{{ getDescendantProp(item, column.field) }}</td>

Here's a working example of the idea: http://plnkr.co/edit/34fKDKReu24381Ox8kdK?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM