Ad

Cannot Iterate Multiple JSON Value

I am trying to use JSON value to view data in ng-repeat. But I am getting only first value. I tried using other method but not getting the value properly.

My JSON response:-

{
  "stylesheet": {
    "attribute-set": [
      {
        "attribute": {
          "_name": "text-align",
          "__prefix": "xsl",
          "__text": "center"
        },
        "_name": "__frontmatter",
        "__prefix": "xsl"
      },
      {
        "attribute": [
          {
            "_name": "space-before",
            "__prefix": "xsl",
            "__text": "80mm"
          },
          {
            "_name": "space-before.conditionality",
            "__prefix": "xsl",
            "__text": "retain"
          },
          {
            "_name": "font-size",
            "__prefix": "xsl",
            "__text": "22pt"
          },
          {
            "_name": "font-weight",
            "__prefix": "xsl",
            "__text": "bold"
          },
          {
            "_name": "line-height",
            "__prefix": "xsl",
            "__text": "140%"
          }
        ],
        "_name": "__frontmatter__title",
        "_use-attribute-sets": "common.title",
        "__prefix": "xsl"
      }
    ],
    "_xmlns:xsl": "http://www.w3.org/1999/XSL/Transform",
    "_xmlns:fo": "http://www.w3.org/1999/XSL/Format",
    "_version": "2.0",
    "__prefix": "xsl"
  }
}

On suggestion from previous question I want to achieve all the datas from "__name" from the "attribute" key.

I tried this as suggested on my controller:-

console.log($scope.jsonObj);
                angular.forEach($scope.jsonObj,function(value,key){
                 console.log(value["attribute-set"][0]["attribute"]["_name"]);
                    });

jsonObj is my JSON object

The output is text-align in my console which is the 1st _name attribute value .

How can I achieve ng-repeat of _name value from this JSON ?

Ad

Answer

The data structure is rather terrible, same objects keys with different data types makes things a little difficult. However this will return you a list of all _name fields.

You then bind that to your scope etc.

data
    .stylesheet['attribute-set']
    .map(x => {
        if (Array.isArray(x.attribute))
            return x.attribute.map(y => y['_name']);
        else
            return [x.attribute['_name']]; 
    })
    .reduce((accu, cur) => accu.concat(...cur), []);

It essentially extracts out the _name field into an array for each attribute set then reduces that into a single array.

See it in action here

Ad
source: stackoverflow.com
Ad