简体   繁体   中英

Manipulating an array of JSON objects

Long story short, I have an array of JSON objects with no keys.I am trying to push each object through HTML, however, I have repeating data that I would like to merge. I am getting this array through an AJAX call, not sure if I should implement something during the call or after.

My Data looks like this:

myData =[{Title:'Test', Dates:'11/12/14-/n11/14/14', Code:'A1B2C3'},
         {Title:'Test', Dates:'10/12/14-/n10/14/14', Code:'D1E2F3'},
         {Title:'Test', Dates:'11/12/14-/n11/14/14', Code:'D1E2F3'},
         {Title:'Test2', Dates:'01/12/14-/n01/14/14', Code:'H1J2K3'}]

The AJAX looks like this:

$.ajax({
    url: ckURL,
    async: false,
    dataType: 'json',
    success: function(data) {
        myData= data;
    }
});

I would love to have myData to look like:

myData =[Test:{Dates:['11/12/14-/n11/14/14','10/12/14-/n10/14/14'], Code:['A1B2C3','D1E2F3']},
         Test2:{Dates:'01/12/14-/n01/14/14', Code:'H1J2K3'}]

Or like this:

myData =[{Title:'Test', Dates:['11/12/14-/n11/14/14','10/12/14-/n10/14/14'], Code:['A1B2C3','D1E2F3']},
         {Title:'Test2', Dates:'01/12/14-/n01/14/14', Code:'H1J2K3'}]

If you have an idea of how to go about this, it would be greatly appreciated. Thank you for reading up to this point.

Hi there and welcome on board!

Map and reduce are your friends.

Here is an example of how to get to the first structure you posted:

myData.reduce((data, item) => {
  const d = data[item.Title];
  if (d) {
    d.Dates.push(item.Dates);
    d.Code.push(item.Code);
  } else {
    data[item.Title] = {
      Dates: [item.Dates],
      Code: [item.Code]
    };
  }
  return data;
}, {}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM