0

Via a JSON call I get this JSON Object:

[
    {
        "feeding_id": 14,
        "supp_name": "Test 1",
        "supp_weight": 20000,
    },
    {
        "feeding_id": 14,
        "supp_name": "Test 2",
        "supp_weight": 1000,
    },
    {
        "feeding_id": 12,
        "supp_name": "Test 1",
        "supp_weight": 4664,
    },
    {
        "feeding_id": 12,
        "supp_name": "Test 2",
        "supp_weight": 2332,
    }
]

What I'm trying to achieve is to create a table like this:

______________________
| 14 | Test 1 | 20000 |
|    | Test 2 |  1000 |
|____|________|_______|
| 12 | Test 1 |  4664 |
|    | Test 2 |  2332 |
|____|________|_______|

I'm more a PHP guy. So I'm trying to loop the Object and put it in a new Object/ Array (in PHP $array[] = array( ... )). But I can't get it done in Javascript/jQuery.

Can someone help me on the way?

2
  • The only doubt I have is the data structure you want to use you can have an object like feeding_id : [ {sups_name: x, supp_weight : y}, {sups_name: x, supp_weight: y} ], is that ok? Commented Aug 6, 2015 at 17:33
  • perhaps you could iterate through the JSON twice? First iteration gets your unique values for "feeding id" to get the arra "IDs" then the second iteration through the JSON checks for "feeding_id" and displays data if it matches .. Commented Aug 6, 2015 at 17:33

5 Answers 5

5

Assuming that the supp_name are unique per feeding_id, you may use the following code (jsonData denoting your original JSON array):

var result = jsonData.reduce( function(acc,rec) { 
  if (!(rec.feeding_id in acc)) acc[rec.feeding_id] = {};
  acc[rec.feeding_id][rec.supp_name]=rec.supp_weight; 
  return acc; 
  }, {} ); 
Sign up to request clarification or add additional context in comments.

2 Comments

Reduce is just going to collapse an array into an object, in this case. There are other ways to achieve the same thing, but here is a fiddle so you can visualize the final outcome. jsfiddle.net/sc21m5sa
Thank you for your answer and explanation. I do understand now. The thing is, that I have more variables in my json object (didn't mention that in my question, sorry for that!). So XPD's answer suits me better. +1 for you afford and neat/ clean code!
1
data.forEach(function(element){
    table[element.feeding_id] = table[element.feeding_id] || []
    table[element.feeding_id].push(element)
})

Working fiddle so you can see the data format change.

https://jsfiddle.net/qgb3ckq6/

Comments

0

Let us assume above json data is in a variable called data. First we can transform the json data array to a different object that can be used to create the table. Then use that object to create the table.

Here in this example table1 is referred to the id of the table.

var obj = {};
for(var i=0;i<data.length;i++){
    var test = obj[data[i]["feeding_id"]];        
    if(!test){
        obj[data[i]["feeding_id"]] = [data[i]];            
    }
    else{
        obj[data[i]["feeding_id"]].push(data[i]);
    }
}
for(key in obj){          
    for(var j= 0;j<obj[key].length;j++){
        var s = $('<tr></tr>'); 
        if(j == 0){
            s.prepend('<td rowspan="'+obj[key].length+'">'+key+'</td>');
        }                
        s.append('<td>'+obj[key][j]["supp_name"]+'</td>');
        s.append('<td>'+obj[key][j]["supp_weight"]+'</td>');
        $('#test1').append(s);
    }



};

will give you with that table. You can use jsfiddle for more on this example. https://jsfiddle.net/5fambjot/.

2 Comments

This answer suits me the best. But another question. Is it possible to sort obj on it's key (DESC)? Already tried changing the order in the PHP code that generates the JSON object, but no luck there.
Or even better, there is also a field 'datetime' inside the JSON object. Is it possible to sort on that field?
0

You can achieve this by following logic

var arr = [
    {
        "feeding_id": 14,
        "supp_name": "Test 1",
        "supp_weight": 20000,
    },
    {
        "feeding_id": 14,
        "supp_name": "Test 2",
        "supp_weight": 1000,
    },
    {
        "feeding_id": 12,
        "supp_name": "Test 1",
        "supp_weight": 4664,
    },
    {
        "feeding_id": 12,
        "supp_name": "Test 2",
        "supp_weight": 2332,
    }
];


var obj = {};

// Creating group by feeding_id
for (var i = 0; i < arr.length; i++) {
    var item = arr[i];
    var id = item.feeding_id;
  var resp = {};  
  if(obj[id] === undefined) {
    resp = {
      "supp_name" : [item.supp_name],
      "supp_weight" : [item.supp_weight]
    }

  } else {
       resp = obj[id];
       resp.supp_name.push(item.supp_name);
       resp.supp_weight.push(item.supp_weight);

  }
  obj[id] = resp;

}

// Iterating over feeding_id map
for(var key in obj) {
    if (obj.hasOwnProperty(key)) {
        console.log(key);
      console.log(obj[key].supp_name);
      console.log(obj[key].supp_weight);
    }
}

For reference - http://plnkr.co/edit/ffshsN8tCE8Tm5puNJCv?p=preview

Comments

0

obj = [{
      "feeding_id": 14,
      "supp_name": "Test 1",
      "supp_weight": 20000,
    }, {
      "feeding_id": 14,
      "supp_name": "Test 2",
      "supp_weight": 1000,
    }, {
      "feeding_id": 12,
      "supp_name": "Test 1",
      "supp_weight": 4664,
    }, {
      "feeding_id": 12,
      "supp_name": "Test 2",
      "supp_weight": 2332,
    }];
$('#content').append($("<table>"));

$.each(obj,function(i, eachVal){
    if( $('tr#feeding_' + eachVal.feeding_id ).length == 0 ){
        var $html = $("<tr></tr>",{
                'id' : 'feeding_' + eachVal.feeding_id,
            });
        $html.append($("<td></td>",{'text':eachVal.feeding_id}));
        $html.append($("<td></td>",{'text':eachVal.supp_name}));
        $html.append($("<td></td>",{'text':eachVal.supp_name}));
        $('#content').find('table').append($html);
    } else {
        var nameRow = $('tr#feeding_' + eachVal.feeding_id ).find('td').eq(1);
        var weightRow = $('tr#feeding_' + eachVal.feeding_id ).find('td').eq(2);
        nameRow.html(nameRow.html() + "<br/>" + eachVal.supp_name)
        weightRow.html(weightRow.html() + "<br/>" + eachVal.supp_weight)
    }
});
td{
    vertical-align:top;
}
table, th, td {
   border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="content"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.