Amboom
Amboom

Reputation: 156

How to access specific properties in a multiple objects using JS

Here is my object:

$scope.info = [];
$scope.info = [{"name":"kanye","size":"","folder":"Folder"},{"name":"west","size":"","folder":"Folder"}]
$scope.infoObj = $scope.info.name;
console.log($scope.infoObj);

This return me Undefined. The response should be like this:

[{"name":kanye},{"name":west}]

But how to access the specific properties from a multiple object using angularJS or jquery/js?

Upvotes: 0

Views: 715

Answers (2)

smaili
smaili

Reputation: 1235

You can actually do a little bit of refactoring to make your code a little cleaner and more readable. Instead of setting your info value twice, set it once, and add the objects in each line after.

Like this:

$scope.info = [];
$scope.info.push({
  "name":"kanye",
  "size":"",
  "folder":"Folder"
});
$scope.info.push({
  "name":"west",
  "size":"",
  "folder":"Folder"
});

See how clean that is? Now it should be fairly obvious that info is an Array of objects, so doing $scope.info.name won't work. What I would recommend is creating a lookup function that can help grab a list based on the key you provide it.

Something like this:

function lookup(key) {
  var result = [];
  for (var i = 0; i < $scope.info.length; i++) {
    var object = {};
    object[key] = $scope.info[i][key];
    result.push(object);
  }
  return result;
}

And then call it like this:

$scope.infoObj = lookup('name');
console.log($scope.infoObj);

Upvotes: 0

ryan
ryan

Reputation: 1084

This should solve the problem:

$scope.infoObj = $scope.info.map(function(obj){ 
  var x = {}; 
  x['name'] = obj['name']; 
  return x;
})

for ES6, it can be simplified to:

$scope.infoObj = $scope.info.map(x => ({name:x['name']}))

Upvotes: 4

Related Questions