Using Javascript, it is possible to generate a new JSON object through manipulation of an already

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/

Answer №1

Perhaps this information can be useful.

To handle the count, a temporary object named temp is used.

{
    "Keystone Foods": {
        "30": {
            "true": 14288,
            "false": 344
        },
        "31": {
            "false": 700,
            "true": 9500
        }
    },
    "Tyson Foods": {
        "32": {
            "false": 227,
            "true": 7049
        },
        "33": {
            "true": 10742,
            "false": 506
        }
    }
}

The code breakdown:

temp = obj1.reduce(function (r, a) {
    // ...
    return r;
}, {}),

This usage of Array.prototype.reduce() involves iterating over obj1, initializing with an empty object and returning results in each iteration.

r[a.supplierName] = r[a.supplierName] || {};

A compact way to create a new object if it doesn't exist already.

{
    "Keystone Foods": {}
}
r[a.supplierName][a.plantId] = r[a.supplierName][a.plantId] || {};

Similar logic for creating objects based on plant ID.

{
    "Keystone Foods": {
        "30": {}
    }
}
r[a.supplierName][a.plantId][a.acptFlag] = a.count;

Assigning the count value under the respective acptFlag property.

{
    "Keystone Foods": {
        "30": {
            "true": 14288
    },
}

With the object setup done, the next focus shifts for constructing a new array containing desired objects o.

obj2 = Object.keys(temp).map(function (k) {
    // ...
    return o;
});

Initially extracting all keys from temp followed by mapping to form a fresh array.

Within the callback function

var o = { supplierName: k };

Creating a new object with supplier name key and current key's value.

Object.keys(temp[k]).forEach(function (kk, i) {
    // ...
});

Further iteration to access the nested keys for plant IDs.

o[i + 1] = '' + temp[k][kk].false + ' / (' + temp[k][kk].false + ' + ' + temp[k][kk].true + ')';

For each plantID, setting up a new property with values representing true and false properties, represented as strings. (Can be adjusted to numbers using

o[i + 1] = temp[k][kk].false / (temp[k][kk].false + temp[k][kk].true);
).

var obj1 = [{...}]; 

document.write('<pre>' + JSON.stringify(temp, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(obj2, 0, 4) + '</pre>');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Decoding JSON Arrays with Newtonsoft in C#

I am struggling to convert this JSON into an object. The concepts of JArray and JToken are proving to be quite confusing for me. I understand that creating a class would help Newtonsoft in mapping the data, but the structure of the objects like: { "a ...

What is the best way to submit a form and display results without refreshing the page?

Imagine having two div elements within a document. The first div serves as the control element, while the second one is designated for displaying a preview of the user's input. HTML <div id="workHere"> <form id="workForm" action="php/crea ...

Associating the object key and value with distinct attributes within the component

person = {name: 'Alice', age: '19', weight: 52} I'm looking to display both the keys and values from the object in one label and input field respectively. I attempted using Object.entries, but couldn't figure out how to sepa ...

looking to showcase the highest 'levelNumber' of elements within an array

arr1 = [ { "levelNumber": "2", "name": "abc", }, { "levelNumber": "3", "name": "abc" }, { "levelNumber": "3", "name": &quo ...

Proper method of defining an action in Vuex

Do you think it's sufficient to create vuex-actions as simple as a1, without chaining then/catch calls? Or should I always go with creating Promises as in a2 (and also adding a reject branch)? Appreciate your insights... import Vue from 'vue& ...

Tips for updating the value of a key in a JavaScript object when the TextField tag's value changes

Here is the schema I am using for my model: const workoutSchema = mongoose.Schema({ workouts: [ { workoutName: String, sets: Number, reps: Number, weight: Number, }, ], }); Below is the postData referenced in the text f ...

Is there a way to make the fixed table header scroll along with the table body data?

I am facing an issue with my table where I have multiple columns. I have managed to fix the table header successfully, however, when I scroll horizontally through the table body columns, the header remains fixed and does not move accordingly. How can I res ...

Combining a JSON object with a regular string in Python

Recently, I encountered a dictionary: (Pdb) interface_list [{'DeviceIndex': 0, 'NetworkInterfaceId': u'eni-2b9dcb04', 'DeleteOnTermination': True}, {'DeviceIndex': 1, 'NetworkInterfaceId': u&apos ...

Ways to retrieve JSON information and incorporate it into an if statement in this specific scenario

Here is the AJAX function code I have written: $('#request_form').submit(function(e) { var form = $(this); var formdata = false; if (window.FormData) { formdata = new FormData(form[0]); } var formAction = form.attr( ...

What is the most effective method for identifying duplicate values in a multidimensional array using typescript or javascript?

I have a 2D array as shown below: array = [ [ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ] ] I am looking to compare the values in the array indexes to check for duplicates. For example array[0] = [1,1]; array[1] = [1,2]; array[2] = [1,1]; We can see that ...

Is it possible to save an entire webpage that infinitely scrolls without actually manually scrolling through it?

I'm dealing with a webpage that has infinite downward scrolling. I tried automating the scrolling, but eventually the page became too large to continue scrolling. To fix this, I manually removed some DIV blocks from the source code which decreased the ...

What is the best way to incorporate a <c:forEach> loop into JSP operations?

I am attempting to calculate the product of two variables that are associated with an item in a loop. Below is the code snippet from the JSP file: <table> <thead> <tr> <th>PRICE</th> <th ...

What is the best way to append these values to an array?

I'm encountering difficulties when trying to add the following array: 637301291068030997 => { guildMemberCount: 4, guildOwnerID: '348832732647784460', guildOwner: 'Ethical Hacker', prefix: '.', guildID: '63730129 ...

Unable to modify the properties of a stateless child component

I'm completely new to React and I decided to create a basic comments application. My main objective was to let users change their display pictures by clicking the 'Change Avatar' button. https://i.sstatic.net/TqVe4.png However, I encountere ...

Javascript text validation is malfunctioning as the alert message fails to appear

Looking for a simple form validation script: <script language=”javascript”> function checkForm(register) { if (""==document.forms.register.FNAME.value){ alert("Please fill out this field!"); document.forms.register.FNAME.focus( ...

Using JavaScript to display dynamic data pulled from Django models

I am currently in the process of designing my own personal blog template, but I have encountered a roadblock when it comes to creating a page that displays previews of all posts. This particular page consists of two columns, #content-column-left and #conte ...

Improving React code by using conditional statements such as IF and Else

Currently, I am delving into the world of React and have managed to devise some logic for rendering a DIV. However, upon reflection, it has become evident that there is redundancy present in my code structure and I am uncertain about how to efficiently ref ...

Creating a link button using JavaScript

I have integrated a Setmore code on my website to facilitate appointment booking, which triggers a popup similar to what you would see on a hotel reservation site. <script id="setmore_script" type="text/javascript" src="https://my.setmore.com/js/iframe ...

Tips for displaying a digital keyboard when a webpage loads on iOS Safari

While developing a website, I noticed that the virtual keyboard fails to appear when an input field gains focus during the page load process. As per Apple's policy restrictions, this functionality is not allowed. However, I am interested in finding a ...

Tips for efficiently resolving and compiling a bug within an NPM package, ensuring it is accessible to the build server

This question may seem a bit unconventional. I am currently using an npm package that includes built-in type definitions for TypeScript. However, I have discovered a bug in these definitions that I am able to easily fix. My goal is to make this updated ve ...