Click here to Skip to main content
15,884,176 members
Articles / Programming Languages / Javascript
Tip/Trick

Find JSON Objects With Same Property and Separate Them

Rate me:
Please Sign up or sign in to vote.
4.44/5 (5 votes)
10 Jun 2015CPOL2 min read 11.8K   7   2
This tip explains how to find the objects with the same property from a JSON and separate them to be shown in the UI.

Introduction

Today, this tip explains how to find the objects with the same property from a JSON and separate them to be shown in the UI. I hope you will like it.

Background

Yesterday, I came across a situation where there was a need to find the objects with the same property from some JSON data and separate them. So I thought of sharing that with you all.

Using the Code

First of all, we will add a jQuery reference as in the following code snippet:

JavaScript
<script src="jquery-2.1.4.min.js"></script>   

Now we need some data, right? Please have a look at the following JSON data:

JavaScript
var data = '[{"name":2014,"data":
[{"x":"1","y":222808746.81}]},{"name":2013,
"data":[{"x":"2","y":289647045.18}]},
{"name":2014,"data":[{"x":"2","y":285136890.07}]},
{"name":2013,"data":[{"x":"3","y":370853178.74}]},
{"name":2014,"data":[{"x":"3","y":403272964.28}]},
{"name":2012,"data":[{"x":"4","y":217294031.36}]},
{"name":2013,"data":[{"x":"4","y":224715039.94}]},
{"name":2014,"data":[{"x":"4","y":249034460.23}]},
{"name":2012,"data":[{"x":"5","y":215978054.15}]},
{"name":2013,"data":[{"x":"5","y":241211810.92}]},
{"name":2014,"data":[{"x":"5","y":245950715.8}]},
{"name":2012,"data":[{"x":"6","y":262898180.85}]},
{"name":2013,"data":[{"x":"6","y":280550623.51}]},
{"name":2014,"data":[{"x":"6","y":295780079.03}]},
{"name":2012,"data":[{"x":"7","y":217310275.85}]},
{"name":2013,"data":[{"x":"7","y":230973675.47}]},
{"name":2014,"data":[{"x":"7","y":238227382.03}]}]';  

Next, we need some UI elements as in the following:

JavaScript
<div id="initialData"></div>
<div id="newData"></div> 
<button id="separateme">Make Me Separate</button>   

What next? We need to show this data to our UI, right? For that, I am calling a function in our document ready function.

JavaScript
$(function () {
        $('#newData').hide(); 
        loadinitialData(); 
    });  

The following is the function definition for the loadinitialData() function.

JavaScript
function loadinitialData() { 
     jsonObject = $.parseJSON(data); 
     var html = '<table><th>Year<
     /th><th>X Value</th><th>Y Value</th>'; 
     for (i = 0; i < jsonObject.length; i++) {    
         html += '<tr><td>' + jsonObject[i].name + 
         '</td><td>' + jsonObject[i].data[0].x + 
         '</td><td>' + 
         jsonObject[i].data[0].y + '</td></tr>';    
     }
     html += '</table>';
     $('#initialData').append(html);
 }    

What we are doing here is parsing our data and appending the data to our UI element using a for loop.
Now after running it, you will get the following output:

Image 1

We have successfully formatted our data and shown it to our UI. Cool, right?

So shall we go and separate our data? I guess you said "Yes". Awesome. Now we will create a click event for our "Make me sort" button as in the following:

JavaScript
$('#separateme').click(function () {    
         loadnewData();    
         $('#separateme').hide();
         $('#newData').show();  
     });  

Here is the definition of the loadnewData() function.

JavaScript
function loadnewData() { 
      for (i = 0; i < uniqueNames.length; i++) {
          var currentName = uniqueNames[i];    
          var uniqueDataArray = $.grep(jsonObject, function (data) {   
              return data.name == currentName;  
          });  
          var html = '<table><th>Year</th>
          <th>X Value</th><th>Y Value</th>'; 
          for (j = 0; j < uniqueDataArray.length; j++) {  
              html += '<tr><td>' + uniqueDataArray[j].name + 
              '</td><td>' + uniqueDataArray[j].data[0].x 
             + '</td><td>' + uniqueDataArray[j].data[0].y + '</td></tr>';   
          }    
          html += '</table>';    
          $('#newData').append(html);    
      }    
 }  

Now, I guess you could determine the difference of both the loadinitialData() and loadnewData() functions. Yeah, you are right, we are using a function "grep" there.

JavaScript
var uniqueDataArray = $.grep(jsonObject, function (data) {
        return data.name == currentName;    
        });   

What our "grep" function does is, it will take all objects at a time that has the property "name" as currentName.

JavaScript
return data.name == currentName;   

Once that is done, we will create a separate HTML table for each property and bind it to our parent element. Shall we now look into the complete code? We have done everything.

Complete Code

JavaScript
<!DOCTYPE html>    
<html>    
<head>    
    <title>Find JSON Object by its property,separate and show demo - Sibeesh Passion</title>  
    <script src="jquery-2.1.4.min.js"></script>    
    <style>    
        #initialData {   
            border: 1px solid #999;   
            width:220px;    
            padding:10px;    
            float:left;    
        }    
        #newData {    
            border: 1px solid #999;    
            width:220px;    
            padding:10px;    
            float:left;    
        }    
         td {    
            border: 1px solid #ccc;    
            padding: 5px;    
            text-align: center;    
        }    
    </style>    
    <script>      
        var data = '[{"name":2014,"data"
        :[{"x":"1","y":222808746.81}]},
        {"name":2013,"data":[{"x":"2",
        "y":289647045.18}]},{"name":2014,"data":
        [{"x":"2","y":285136890.07}]},
        {"name":2013,"data":[{"x":"3",
        "y":370853178.74}]},{"name":2014,"data":
        [{"x":"3","y":403272964.28}]},
        {"name":2012,"data":[{"x":"4",
        "y":217294031.36}]},{"name":2013,"data":
        [{"x":"4","y":224715039.94}]},{"name":2014,
        "data":[{"x":"4","y":249034460.23}]},
        {"name":2012,"data":[{"x":"5",
        "y":215978054.15}]},{"name":2013,"data":
        [{"x":"5","y":241211810.92}]},{"name":2014,
        "data":[{"x":"5","y":245950715.8}]},
        {"name":2012,"data":[{"x":"6",
        "y":262898180.85}]},{"name":2013,"data":
        [{"x":"6","y":280550623.51}]},
        {"name":2014,"data":[{"x":"6",
        "y":295780079.03}]},{"name":2012,"data":
        [{"x":"7","y":217310275.85}]},{"name":2013,
        "data":[{"x":"7","y":230973675.47}]},
        {"name":2014,"data":
        [{"x":"7","y":238227382.03}]}]';    

        var jsonObject;    
        var uniqueNames = [2013, 2012, 2014]; 
        $(function () {    
            $('#newData').hide();    
            loadinitialData();    
            $('#separateme').click(function () { 
                loadnewData();    
                $('#separateme').hide();    
                $('#newData').show();    
            });    
        });    
        function loadinitialData() {    
            jsonObject = $.parseJSON(data);    
            var html = '<table><th>Year</th>
            <th>X Value</th><th>Y Value</th>';    
            for (i = 0; i < jsonObject.length; i++) {    
                html += '<tr><td>' + jsonObject[i].name + '</td><td>' + 
                jsonObject[i].data[0].x + '</td>
                <td>' + jsonObject[i].data[0].y + '</td></tr>';    
            }    
            html += '</table>';    
            $('#initialData').append(html);    
        }    
        function loadnewData() {          
            for (i = 0; i < uniqueNames.length; i++) {   
                var currentName = uniqueNames[i];    
                var uniqueDataArray = $.grep(jsonObject, function (data) {    
                    return data.name == currentName;    
                });    
                var html = '<table><th>Year</th>
                <th>X Value</th><th>Y Value</th>';    
                for (j = 0; j < uniqueDataArray.length; j++) {    
                    html += '<tr><td>' + uniqueDataArray[j].name + 
                    '</td><td>' + uniqueDataArray[j].data
                    [0].x + '</td><td>' + 
                    uniqueDataArray[j].data[0].y + '</td></tr>';    
                }    
                html += '</table>';    
                $('#newData').append(html);    
            }  
        }      
    </script>    
</head>    
<body>    
    <div id="initialData"></div>   
    <div id="newData"></div>    
    <button id="separateme">Make Me Separate</button>   
</body>    
</html>    

Now it is time to see our output as in the following:

Image 2

You can find we have separated our object and shown it in a separate table. Cool. That is all for the day. I will return with another article soon.

Conclusion

I hope you liked this tip. Please share with me your valuable thoughts and comments. Your feedback is always welcome.

Thanks in advance. Happy coding!

History

  • 10th June, 2015: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Germany Germany
I am Sibeesh Venu, an engineer by profession and writer by passion. I’m neither an expert nor a guru. I have been awarded Microsoft MVP 3 times, C# Corner MVP 5 times, DZone MVB. I always love to learn new technologies, and I strongly believe that the one who stops learning is old.

My Blog: Sibeesh Passion
My Website: Sibeesh Venu

Comments and Discussions

 
QuestionGood one, a suggestion Pin
Afzaal Ahmad Zeeshan11-Jun-15 22:57
professionalAfzaal Ahmad Zeeshan11-Jun-15 22:57 
AnswerRe: Good one, a suggestion Pin
Sibeesh Passion11-Jun-15 23:22
professionalSibeesh Passion11-Jun-15 23:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.