-5

I have this json file I want parse and get value of subcat for test1 as an array in javascript. Is there an easy way to do this? I have used AngularJS $http to get the json.

For the input:

[
   {
    "category":"test1",
    "ID":"1",
      "subcat":[
        {
         "completed":"4",
         "uncompleted":"5"
        }
     ]
   },{
    "category":"test2",
    "ID":"2"
    "subcat":[
        {
         "completed":"1",
         "uncompleted":"5"
        }
   }

]

Expected result is [4,5]

Obscure Geek
  • 749
  • 10
  • 22
user2286483
  • 169
  • 1
  • 3
  • 11

3 Answers3

1
Corrected Array 


 [
       {
         "category":"test1",
          "subcat":[
                    {
                      "completed":"4",
                      "uncompleted":"5"
                     }
                   ]
       },
       {
          "category":"test2",
          "subcat":[
                    {
                      "completed":"1",
                      "uncompleted":"5"
                    }
                   ]
         }
    ]
var JsonArray=[
                {
                  "category":"test1",
                  "subcat":[{"completed":"4","uncompleted":"5"}]}, 
                {
                  "category":"test2",
                  "subcat":[{"completed":"1","uncompleted":"5"}]
                }
              ];
for(var i=0;i<JsonArray.length;i++)
      {
          if(JsonArray[i].category=="test1")
            var Res=JsonArray[i].subcat;
      }

"Res" will contain your desired result; If you want array as [4,5] Then

var finalRes=[];
finalRes.push(Res[0].completed);
finalRes.push(Res[0].uncompleted);
kavetiraviteja
  • 2,058
  • 1
  • 15
  • 35
0

Try this...

     <script type="text/javascript">
      var newarray=new Array();
var test='[{"category":"test1","ID":"1","subcat":[{"completed":"4","uncompleted":"5"}]},{"category":"test2","ID":"2","subcat":[{"completed":"1","uncompleted":"5"}]}]';

var tags = JSON.parse(test);

for(i=0;i<tags.length;i++)
{

if(tags[i]['category']=='test1')
{
var subcat=tags[i]['subcat'];
for(j=0;j<subcat.length;j++)
{
newarray.push(subcat[j]['completed']);
newarray.push(subcat[j]['uncompleted']);
}

}
}
console.log(newarray);
      </script>

Output:["4", "5"]

DEMO:https://jsfiddle.net/t4yfb923/

Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50
-1

You can use lodash and the method find : https://lodash.com/docs#find

// Stock your json in a variable
var json = [
   {
    "category":"test1",
    "ID":"1",
      "subcat":[
        {
         "completed":"4",
         "uncompleted":"5"
        }
     ]
   },{
    "category":"test2",
    "ID":"2"
    "subcat":[
        {
         "completed":"1",
         "uncompleted":"5"
        }
   }

]

//find your object with lodash
var result = _.find(json, {"ID": "1"});

//then, get subcat value
console.log(result.subcat) 
Alexandre
  • 1,940
  • 1
  • 14
  • 21