2

I am getting below result through ajax and the data which I get in ajax success is

[{
  "plants_ref_id": "1",
  "plant_name": "MCW",
  "employees_data": "6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000"
},{
  "plants_ref_id": "3",
  "plant_name": "SJCPL",
  "employees_data": "4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385"
}]

I am trying to convert this data to format

[{
  name: 'MCW',
  data: [6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000
]},{
  name: 'SJCPL',  
  data: [4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385]
}]

I am trying to convert to this format for generating highcharts as https://jsfiddle.net/mcj075jf/

How do I convert to the above format in jQuery using for loop or $.each. Please help.

2 Answers 2

1

You can use map as follows:

var plants = [{
  "plants_ref_id": "1",
  "plant_name": "MCW",
  "employees_data": "6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000"
},{
  "plants_ref_id": "3",
  "plant_name": "SJCPL",
  "employees_data": "4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385"
}];

var formattedData = plants.map((plant) => ({
  name: plant.plant_name,
  data: plant.employees_data.split(',').map((data) => parseFloat(data))
}));

console.log(formattedData);

Sign up to request clarification or add additional context in comments.

3 Comments

If I pass the same data to highcharts graph is not displaying. Please check here jsfiddle.net/mcj075jf/1
@rjirji I guess we need to convert that array of strings to numbers. Check my edited answer :)
I changed your jsfiddle to use my edited answer with the fix and it is working now!jsfiddle.net/17rf4ugt
0

Here you go with the solution https://jsfiddle.net/z10jheo2/

var data = [{
  "plants_ref_id": "1",
  "plant_name": "MCW",
  "employees_data": "6,6,80,70,60,30,2,3,12,12,37.00,60.00,64666.666667,8000.0000"
},{
  "plants_ref_id": "3",
  "plant_name": "SJCPL",
  "employees_data": "4,5,6,7,7,7,6,4,4,5,20.00,3.00,176923.076923,38461.5385"
}];

var newData = [];

for(var i=0; i<data.length; i++) {
   var tempData = {};
   tempData.name = data[i].plant_name;
   tempData.data = data[i].employees_data.split(',');
   newData.push(tempData); 
   console.log(newData);
}

2 Comments

If I pass the same data to highcharts graph is not displaying. Please check here jsfiddle.net/z10jheo2/1
Here you go with the solution jsfiddle.net/17rf4ugt . Since I was spliting data on the basis of comma, we need to revert back to float to populate the chart.

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.