3

I am new to the web Development. I do have an json obj which is like

$scope.jsonData =     {
        "messages": {
            "A": [{
                "missingFields": [{
                    "RESPONSIBILITY": ""
                }],
                "temporaryId": 2,
                "messages": "",
                "id": 2,
                "content": ""
            }, {
                "missingFields": [{
                    "RESPONSIBILITY": ""
                }],
                "temporaryId": 3,
                "messages": "",
                "id": 3,
                "content": ""
            }, {
                "missingFields": [{
                    "RESPONSIBILITY": ""
                }],
                "temporaryId": 4,
                "messages": "",
                "id": 4,
                "content": ""
            }],
            "B": [{
                "missingFields": [{
                    "CITY": ""
                }, {
                    "PINCODE": ""
                }],
                "messages": "No Address details found.",
                "id": -1,
                "content": ""
            }]
        }
     }

Now I want to iterate through this object and I want to get the "RESPONSIBILITY" field.Here I tried like -

for (var i=0; i < $scope.jsonData.messages.length; i++) {
}

But it is giving the length of the messages as undefined. SO, and also I want to use that in the angular code . I used like -

ng-repeat="suggestion in jsonData.messages

Can any one please explain me this . I searched a lot and tried so I am asking this question.

ganesh
  • 875
  • 2
  • 14
  • 26

2 Answers2

3

You need to have nested loops and use Object.keys to get the key

Like:

for ( var k in jsonData.messages ) {
   jsonData.messages[k].forEach((v)=>{

       let tID = v.temporaryId || ""; //Get the temporaryId
       console.log( tID );

       v.missingFields.forEach((o)=>{
           //Object.keys(o)[0] <-- To get the first key of the object
           console.log( Object.keys(o)[0] );
       });
   });
}

To make a simplified array, you can use Object.values and map the values.

let jsonData = {
  "messages": {
    "A": [{
      "missingFields": [{
        "RESPONSIBILITY": ""
      }],
      "temporaryId": 2,
      "messages": "",
      "id": 2,
      "content": "CONTENT 1"
    }, {
      "missingFields": [{
        "RESPONSIBILITY": ""
      }],
      "temporaryId": 3,
      "messages": "",
      "id": 3,
      "content": ""
    }, {
      "missingFields": [{
        "RESPONSIBILITY": ""
      }],
      "temporaryId": 4,
      "messages": "",
      "id": 4,
      "content": ""
    }],
    "B": [{
      "missingFields": [{
        "CITY": ""
      }, {
        "PINCODE": ""
      }],
      "messages": "No Address details found.",
      "id": -1,
      "content": ""
    }]
  }
}

let simplified = Object.values(jsonData.messages).map((v) => {
  let t = [];
  v.forEach(o => {
    t.push({
      temporaryId: o.temporaryId || "",
      missingFields: o.missingFields.map((x) => Object.keys(x)[0]),
      content: o.content || ""
    });
  });
  return t;
}).reduce((c, v) => c.concat(v), []);

console.log(simplified);

Using just for loops.

var simplified = [];
for ( var k in jsonData.messages ) {
    for ( var i in jsonData.messages[k] ) {
        var temporaryId = jsonData.messages[k][i].temporaryId;
        var content = jsonData.messages[k][i].content;
        var missingFields = [];

        for ( var x in jsonData.messages[k][i].missingFields ) {
            for ( var y in jsonData.messages[k][i].missingFields[x] ) missingFields.push( y );
        }

        simplified.push({
          temporaryId: temporaryId,
          missingFields: missingFields,
          content: content
        });
    }
}
Eddie
  • 26,040
  • 6
  • 32
  • 55
  • One thing, Here How can I use this to get the temporaryId in template of html in ng-repeat="suggestion in jsonData.messages . – ganesh Mar 09 '18 at 14:28
  • I added the code to access the temporaryId @ganesh – Eddie Mar 09 '18 at 14:32
  • Yes, Thanks a lot.Can I ask you one more question ? – ganesh Mar 09 '18 at 14:34
  • Happy to help. Sure. – Eddie Mar 09 '18 at 14:34
  • Here, Now From this data I want to create one more object which will read from the way you did and will create an object. Like - – ganesh Mar 09 '18 at 14:35
  • I dont understand. You mean, you want to make a simplified array or object to loop thru angular? – Eddie Mar 09 '18 at 14:39
  • Here, Now From this data I want to create one more object which will read from the way you did and will create an object. Like - var jsonObj=messages:{ temporyId: 3, "missingFields": [{ "RESPONSIBILITY": "" }], content:" " } such type of object. – ganesh Mar 09 '18 at 14:41
  • Yes, From this I want to have a simplified array, which I can iterate easily, Like the one which I have added in my previous comment. – ganesh Mar 09 '18 at 14:42
  • Yeah, we can make a simplified array. But the one you provided is not a valid array or object. What data do you want to include in the simplified array? `temporyId`, `missingFields` and `contents`? – Eddie Mar 09 '18 at 14:44
  • Yes, that data I want to add in that array. – ganesh Mar 09 '18 at 14:45
  • One more thing, what if there is no `temporyId` like on your example. The one on the `B` object – Eddie Mar 09 '18 at 14:46
  • No, temporyId will always be there. – ganesh Mar 09 '18 at 14:47
  • Okay I will check immediately. – ganesh Mar 09 '18 at 15:01
  • Excellent.. Eddie, You are Such a gem. Thanks a lot for your Help . :-) Means a lot. – ganesh Mar 09 '18 at 15:05
  • Happy to help @ganesh – Eddie Mar 09 '18 at 15:06
  • Hey, Now Here there is one problem , you are using arrowfunction here, now when I run test cases it is failing – ganesh Mar 16 '18 at 07:16
  • Are you not allowed to use arrow function? – Eddie Mar 16 '18 at 07:18
  • yes , even it is giving error for using let keyword – ganesh Mar 16 '18 at 07:19
  • SyntaxError: Unexpected token '>' – ganesh Mar 16 '18 at 07:19
  • Where are you getting that error? On your browser? Or on your IDE? – Eddie Mar 16 '18 at 07:20
  • I mean whenI run test cases which I have written in karma – ganesh Mar 16 '18 at 07:22
  • I am using angular 1 and it is not supporting – ganesh Mar 16 '18 at 07:22
  • Those are new JS feature. Ill try to make an old loop. One moment. – Eddie Mar 16 '18 at 07:24
  • Hey eddie, Right now I am trying to add a key to a json .missingDataValues.push({ [$scope.missingData[i].missingFields[j]]: value }); So, Here [$scope.missingData[i].missingFields[j]] this works fine but again the same Problem ES6. Can you tell me how can I add this dynamic key to this json? – ganesh Mar 16 '18 at 08:10
  • Yes that is ES6, You need to make a multiple lines of codes for that to be replaced. – Eddie Mar 16 '18 at 08:17
  • `var tempObj = {}; tempObj[$scope.missingData[i].missingFields[j]] = value; .....missingDataValues.push( tempObj ); ` – Eddie Mar 16 '18 at 08:17
  • Try that one, and next time, we need to be on topic here is SO, which mean only related questions/inquiries for each post. :) – Eddie Mar 16 '18 at 08:18
  • Okay Thanks actually I did in the same way – ganesh Mar 16 '18 at 08:29
  • Hi @Eddie Can you please look at this https://stackoverflow.com/questions/49420541/highlight-a-string-from-the-text-document-by-adding-spans/49422020#49422020 Sorry For telling you this but I was facing this issue, you are good with JS So just seeking for some help If I can get, It will be really helpful – ganesh Mar 23 '18 at 06:38
  • Its like the highlighting of the text from the text document – ganesh Mar 23 '18 at 08:14
0
const flatten = [].concat.apply([], Object.values(jsonData.messages))
const result = [].concat.apply([], flatten.map(item => item.missingFields))
oldmayn
  • 141
  • 1
  • 1
  • 14
  • While this code may answer the question, providing additional context regarding **how** and **why** it solves the problem would improve the answer's long-term value. – Alexander Mar 09 '18 at 15:53