Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group array entries in javascript

I have this sample data and transformed it into an array of objects like the one below. This has two levels: Level1, and Level2.

var array = [{
  "Level1": "Assigned to",
  "Level2": "Assigned To 1"
}, {
  "Level1": "Assigned to",
  "Level2": "Assigned To 2"
}, {
  "Level1": "Assigned to",
  "Level2": "Assigned To 3"
}, {
  "Level1": "Location1",
  "Level2": "SubLocation 1"
}, {
  "Level1": "Location1",
  "Level2": "SubLocation 2"
}];

I want to group it by their Key, and below it will be the name/values of the key. (see sample below). How will I fix this so that in my HTML it will be.

<div id="accordion">
  <h3>Assigned to</h3>
  <div>
    <p>Assigned To 1</p>
    <p>Assigned To 2</p>
    <p>Assigned To 3</p>
  </div>
  <h3>Location</h3>
  <div>
    <p>SubLocation 1</p>
    <p>SubLocation 2</p>
  </div>
</div>
like image 258
Aventus Avatar asked May 14 '26 09:05

Aventus


1 Answers

Using $.each() you can iterate through the array and get values, them manipulate them.

var json = [{
  "Level1": "Assigned to",
  "Level2": "Assigned To 1"
}, {
  "Level1": "Assigned to",
  "Level2": "Assigned To 2"
}, {
  "Level1": "Assigned to",
  "Level2": "Assigned To 3"
}, {
  "Level1": "Location1",
  "Level2": "SubLocation 1"
}, {
  "Level1": "Location1",
  "Level2": "SubLocation 2"
}];

var LevelArray = []
$.each(json, function(i, val){
  //console.log(val);
  var className =  val.Level1.replace(/\s/g);
  if($.inArray(className, LevelArray) == -1){
    LevelArray.push(className);
    var thisLevel = $('<div>',{
      'class' : className
    });
    thisLevel.append($('<h3>').text(val.Level1));
    var thisRow = $('<div>').append($('<p>').text(val.Level2));
    thisLevel.append(thisRow);
    $('body').append(thisLevel);
  } else {
    var thisLevel = $('.' + className )
    thisLevel.find('div').append($('<p>').text(val.Level2));
  
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
like image 156
rrk Avatar answered May 15 '26 21:05

rrk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!