Mr.Ayanlar Mr.Ayanlar - 15 days ago 5
Javascript Question

JSON convert with Javascript

I have a json file like as below


[{
"id": 2,
"name": "Ali",
"records":[{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
},{
"id": 3,
"name": "Mete",
"records":[{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}]


I want to convert to like this


[{
"id": 2,
"name": "Ali",
record: {
"type": "L",
"total": 123
}
},{
"id": 2,
"name": "Ali",
record: {
"type": "P",
"total": 102
}
},{
"id": 3,
"name": "Mete",
record: {
"type": "O",
"total": 100
}
},{
"id": 3,
"name": "Mete",
record: {
"type": "T",
"total": 88
}
}]


how can i do it using javascript?

Answer

Here is what you could do. However, this doesn't work in IE as is as Object.assign that is being used, isn't yet supported in IE. However, it could be replaced with any javascript object clone methods.

You could check : What is the most efficient way to deep clone an object in JavaScript?

var input = [{
  "id": 2,
  "name": "Ali",
  "records": [{
    "type": "L",
    "total": 123
  }, {
    "type": "P",
    "total": 102
  }]
}, {
  "id": 3,
  "name": "Mete",
  "records": [{
    "type": "O",
    "total": 100
  }, {
    "type": "T",
    "total": 88
  }]
}];


var output = [];
input.forEach((obj) => {
  var records = obj.records;
  delete obj.records;

  records.forEach((record) => {
    // Doesnt have any support in IE.
    var newRecord = Object.assign({}, obj);
    newRecord.record = record;
    output.push(newRecord);
  });
});

console.log(output);

If you are fine to use jQuery, here is what you could do.

var input = [{
  "id": 2,
  "name": "Ali",
  "records": [{
    "type": "L",
    "total": 123
  }, {
    "type": "P",
    "total": 102
  }]
}, {
  "id": 3,
  "name": "Mete",
  "records": [{
    "type": "O",
    "total": 100
  }, {
    "type": "T",
    "total": 88
  }]
}];


var output = [];
input.forEach((obj) => {
  var records = obj.records;
  delete obj.records;

  records.forEach((record) => {
    var newRecord = jQuery.extend({}, obj);
    newRecord.record = record;
    output.push(newRecord);
  });
});

console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>