I have a JSON object that I am manipulating to create a new JSON object. The challenge lies in dynamically constructing a part of the JSON object. Below is the original JSON object:
[{"acptFlag":true,"count":14288,"limsFlag":true,"plantId":30,"plantName":"Camilla, GA","supplierId":20,"supplierName":"Keystone Foods"},{"acptFlag":false,"count":344,"limsFlag":true,"plantId":30,"plantName":"Camilla, GA","supplierId":20,"supplierName":"Keystone Foods"},{"acptFlag":false,"count":700,"limsFlag":true,"plantId":31,"plantName":"Albany, KY","supplierId":20,"supplierName":"Keystone Foods"},{"acptFlag":true,"count":9500,"limsFlag":true,"plantId":31,"plantName":"Albany, KY","supplierId":20,"supplierName":"Keystone Foods"},{"acptFlag":false,"count":227,"limsFlag":true,"plantId":32,"plantName":"Green Forest, AR","supplierId":21,"supplierName":"Tyson Foods"},{"acptFlag":true,"count":7049,"limsFlag":true,"plantId":32,"plantName":"Green Forest, AR","supplierId":21,"supplierName":"Tyson Foods"},{"acptFlag":true,"count":10742,"limsFlag":true,"plantId":33,"plantName":"Dawson, GA","supplierId":21,"supplierName":"Tyson Foods"},{"acptFlag":false,"count":506,"limsFlag":true,"plantId":33,"plantName":"Dawson, GA","supplierId":21,"supplierName":"Tyson Foods"}]
The desired JSON object is as follows:
[{"supplierName":"Keystone Foods","1":(344/(344+14288)) , "2":700/(700+9500))}},{"supplierName":"Tyson Foods"","1":(227/(227+7049)) , "2":(506/(506+10742))}}]
Here, I am attempting to group data for each supplier into a single object. In
"1":(344/(344+14288)) , "2":700/(700+9500))
, false count/true count ratio is represented by "1
" and "2
" signifies the count of plants. Confusion arises in constructing the plant count code.
Below is my existing code:
var resultJSON = {}, arr = [];
var jsonObj = JSON.parse(obj)
for (var key in jsonObj) {
if (jsonObj.hasOwnProperty(key)) {
var val = jsonObj[key];
var supplierName = val.supplierName;
arr.push(supplierName);
}
}
var M = {}, R = []
getUniqueSuppliers(arr)
function getUniqueSuppliers(arr) {
for(var i = 0; i < arr.length; i++) {
M[arr[i]] = "supplierName"
}
for(var i in M) {
R.push(i)
}
}
checkEachSupplier(R)
function checkEachSupplier(R) {
for (var index = 0; index < R.length; index++) {
var supplierName = R[index]
createNewJSON(supplierName)
}
}
getPlantTotalValueBasedOnSupplier(R);
function createNewJSON(supplierName) {
for (var key in jsonObj) {
if (jsonObj.hasOwnProperty(key)) {
var val = jsonObj[key];
if(supplierName == val.supplierName) {
resultJSON[supplierName] = {"supplierName" : supplierName}
}
}
}
}
console.log(resultJSON)
Link to my JSON fiddle: https://jsfiddle.net/7u5qphx9/6/