Marcus Henningsen
Marcus Henningsen

Reputation: 55

Split json object by name

I'm looking for the smartest way to split a json object by name and I haven't found the right answer yet.

The json looks like this:

[{
    "Date": "2016-02-17",
    "ProductionAvg": 0.014558
}, {
    "Date": "2016-02-18",
    "ProductionAvg": 0.014154
}]

I need to split the object into arrays with just the values of each pair:

[2016-02-17, 2016-02-18]

and

[0.014558, 0.014154]

The code I've come up with so far is:

var date = []
var production = []

$.each(data, function () {
    $.each(this, function (name, value) {
        if (name == "Date") {
          date.push(value);
        }
        if (name == "ProductionAvg") {
          production.push(value);
        }
      }
    });
});

However, as I newbie I'm not at all sure whether this is the standard way of achieving this. Any comments are much appreciated.

Upvotes: 2

Views: 644

Answers (4)

tomtom
tomtom

Reputation: 642

You can use the higher-order function map to create new arrays from an array.

If you save your json into a variable arr you can do this:

var dates = arr.map(x=>{
   return x.Date;
});

var production = arr.map(x=>{
   return x.ProductionAvg;
});

Upvotes: 1

baao
baao

Reputation: 73301

As you're looking for the smartest way, use plain javascript.

var arr = [{
    "Date": "2016-02-17",
    "ProductionAvg": 0.014558
}, {
    "Date": "2016-02-18",
    "ProductionAvg": 0.014154
}];

function groups(arr) {
    var obj = {};
    arr.forEach(function(val) {
        var keys = Object.keys(val);
        keys.forEach(function(v) {
            if (obj[v]) {
                return obj[v].push(val[v]);
            } 
            obj[v] = [val[v]];
        });
    });

    return obj;
}

console.log(groups(arr))

Upvotes: 1

Shashank
Shashank

Reputation: 2060

Here's a better way of doing that by making use of hasOwnProperty. Moreover, by making nested $.each which isn't required, you are hindering the performance of the application.

Please find the code here.

Code:

var data = [{
    "Date": "2016-02-17",
    "ProductionAvg": 0.014558
}, {
    "Date": "2016-02-18",
    "ProductionAvg": 0.014154
}];
var date = []
var production = []

$.each(data, function (key, value) {
    if (value.hasOwnProperty('Date')) {
        date.push(value.Date);
    }
    if (value.hasOwnProperty('ProductionAvg')) {
        production.push(value.ProductionAvg);
    }
});

document.write('date = ' + date + ', Production = ' + production);
console.log(date, production);

Upvotes: 1

Rhumborl
Rhumborl

Reputation: 16609

There is nothing wrong with what you have, as long as you know all the property names.

If you want to make it a bit neater and more dynamic, you can store all the results in another object, with each property having the same name as the source property and value being the extracted values from that source, e.g.

{
    "Date": ["2016-02-17", "2016-02-18"],
    "ProductionAvg": [0.014558, 0.014154]
}

This just requires checking the property exists in the result object and if not, setting it to an empty array. Then just push the current value to it:

var arr = [{
  "Date": "2016-02-17",
  "ProductionAvg": 0.014558
}, {
  "Date": "2016-02-18",
  "ProductionAvg": 0.014154
}]

results = {};
$.each(arr, function() { // loop array
  $.each(this, function(k, v) { // loop object
    // if result does not have property name, create it with empty array
    if(typeof(results[k]) === "undefined") {
      results[k] = [];
    }
    
    // push the value to the result array
    results[k].push(v);
  })
});

console.dir(results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 2

Related Questions