0

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?

3
  • 1
    Note that [] means Array, which are generally accessed with things like [0], so maybe you should try $scope.info[0].name Commented Apr 21, 2016 at 3:03
  • I tried it already but only the value from info[0].name showed. Example: {"name": kanye}. Commented Apr 21, 2016 at 3:09
  • The console should print kanye as that's the name of the first object, the one in the [0] position in the array. To get the second one you'd do $scope.info[1].name etc. Commented Apr 21, 2016 at 3:13

2 Answers 2

4

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']}))
Sign up to request clarification or add additional context in comments.

1 Comment

or $scope.info.map(obj=>({name: obj.name});
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.