1

I am getting this type of json in my $scope of angularjs:

$scope.someStuff = {
      "id": 2,
      "service": "bike",
      "min": "22",
      "per": "100",
      "tax": "1",
      "categoryservices": [
        {
          "id": 32,
          "category": {
            "id": 1,
            "name": "software"
          }
        },
        {
          "id": 33,
          "category": {
            "id": 2,
            "name": "hardware"
          }
        },
        {
          "id": 34,
          "category": {
            "id": 3,
            "name": "waterwash"
          }
        }
      ]
    }

I want to use angularjs forEach loop and i want to get only category name,

My expected output:

[{"name":"software"}, {"name":"hardware"}, {"name":"waterwash"}]
1
  • $scope.someStuff.categoryservices.map((x) => { return { name: x.category.name}}) Commented Mar 16, 2018 at 9:42

2 Answers 2

1

You can use Array.map()

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

$scope.someStuff.categoryservices.map((x) => { return { name: x.category.name}}) 

var obj = {
  "id": 2,
  "service": "bike",
  "min": "22",
  "per": "100",
  "tax": "1",
  "categoryservices": [{
      "id": 32,
      "category": {
        "id": 1,
        "name": "software"
      }
    },
    {
      "id": 33,
      "category": {
        "id": 2,
        "name": "hardware"
      }
    },
    {
      "id": 34,
      "category": {
        "id": 3,
        "name": "waterwash"
      }
    }
  ]
};

console.log(obj.categoryservices.map((x) => {
  return {
    name: x.category.name
  }
}))

Sign up to request clarification or add additional context in comments.

Comments

1

You can use map method by passing a callback function as parameter.

const someStuff = { "id": 2, "service": "bike", "min": "22", "per": "100", "tax": "1", "categoryservices": [ { "id": 32, "category": { "id": 1, "name": "software" } }, { "id": 33, "category": { "id": 2, "name": "hardware" } }, { "id": 34, "category": { "id": 3, "name": "waterwash" } } ] }   
let array = someStuff.categoryservices.map(function({category}){
  return {'name' : category.name}
});
console.log(array);

Comments

Your Answer

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