0

Simplest way to count a specific property on imported json? I'm trying to get a count of status "success" Tried pipes and I'm very confused

myjson: {
    company1 : {
        status : "success",
    },
  company2 : {
    status : "failure",
  },
  company1 : {
    status : "success",
  },    
}
limonik
  • 499
  • 1
  • 6
  • 28
SD Dev
  • 335
  • 3
  • 10
  • Can be a typo, but this is not valid JSON, object cannot contain the same property (named company1) twice – Petr Adam Jul 13 '16 at 13:50

2 Answers2

0

If you don't know what exact properties (company1, company2, ...) your JSON can contain, you need firstly to extract them.

Since objects in javascript can be accessed in similar manners like arrays, you can easy iterate all properties with for (var property in myjson) and access its values like myjson[property]

Try something like this:

var myjson = {
    company1: { status: "success", },
    company2: { status: "failure", },
    company3: { status: "success", },
};

var count = 0;

for (var property in myjson)
{
    if (myjson.hasOwnProperty(property) && myjson[property].status == "success")
    {
        count++;
    }
}

For more information about iterating object of unknown structure, check this post Iterate through object properties

Community
  • 1
  • 1
Petr Adam
  • 1,425
  • 11
  • 23
0

You can do an old fashioned object iteration, but I don't know how to deal with duplicate keys like in your code.

var companies = {
  company1: {
    status: "success",
  },
  company2: {
    status: "failure",
  },
  company3: {
    status: "success",
  }
}

var successCount = 0;

for (var company in companies) {
  var company = companies[company];
  for (var status in company) {
    if(company[status] === 'success') {
        successCount++;
    }
  }
}

document.getElementById('success').innerHTML = successCount;

See example https://jsfiddle.net/rogtao73/

Michelangelo
  • 5,888
  • 5
  • 31
  • 50