dnagirl
dnagirl

Reputation: 20446

Easy way to extract json object properties into an array?

Given the following JSON object, is there an easy way to extract just the values of the results object properties?

var j={"success":true,
       "msg":["Clutch successfully updated."],
       "results":{"count_id":2,
                  "count_type":"Clutch",
                  "count_date":"2000-01-01",
                  "fish_count":250,
                  "count_notes":"test"}
      };

var arr= doSomething(j.results);
//arr=[2, "Clutch","2000-01-01",250,"test"]

Upvotes: 5

Views: 7355

Answers (2)

Robert
Robert

Reputation: 21388

Your function would be something like

var doSomething = function (obj) {
    var arr = [];
    for (var x in obj) if (obj.hasOwnProperty(x)) {
        arr.push(obj[x]);
    }
    return arr;
}

Upvotes: 5

John Hartsock
John Hartsock

Reputation: 86892

function resultstoArray (resultsData) {
  var myArray = new Array();
  for (var key in resultsData) {
    myArray.push(resultsData[key]);
  }
  return myArray;
}

var arr = resultsToArray(j.results);

Upvotes: 2

Related Questions