Generate a new item using an existing one

I am seeking to extract the desired output from the provided input:

Input Configuration:

var inputParams = { 
    'inputDetails' :[
        { 'field' : 'specificationName', 'value' : 'strong'},
        { 'field' : 'specificationName', 'value' : 'weak'},
        { 'field' : 'specificationName', 'value' : 'energetic'}
        { 'field' : 'incident', 'value' : '123'},
        { 'field' : 'groupId', 'value' : 'g1'},
        { 'field' : 'groupId', 'value' : 'group1'},
    ]
};

Desired Output Format:

var outputParams = {
    'paramDetail': [
        { 'field' : 'specificationName', 'value' : [ 'strong ', 'weak' ,'energetic']},
        { 'field' : 'incident', 'value' : ['123']},
        { 'field' : 'groupId', 'value' : ['g1', 'group1']},
    ] 
};

The logic implementation I have attempted is:

var changedList = {
                   changedJsonObject : []
                  };
var i = 0 ;
var prev;
var firstTime = true;
var index = 0;
var facetfields = ['strong', 'weak' ,'energetic'];
do {
    if (!params[index].field.localeCompare(facetFields[i])) {
        if (prev == null) {
            prev = params[index].field;
        }
        console.log(index + " " + params[index].field + " " + params[index].value);
        if (!prev.localeCompare(params[index].field)) {
            if (firstTime) {
                console.log("create");
                outputParams.paramDetail.push({
                    "field": params[index].field,
                    "value": [params[index].value]
                });
                firstTime = false;
            } else {
                console.log("update");
                for (var tempInd = 0; tempInd < outputParams.paramDetail.length; tempInd++) {
                    if (!outputParams.paramDetail[tempInd].field.localeCompare
                         (params[index].field)) {
                        outputParams.paramDetail[tempInd].value =
                            outputParams.paramDetail[tempInd].value + "," + params[index].value;
                        break;
                    }
                }
            }
        }
    } else {
        i++;
        index = index - 1;
        firstTime = true;
        prev = null;
    }
}
index++;
}
while (index < params.length);
for (var s in outputParams.paramDetail) {
    console.log(outputParams.paramDetail[s].field);
    console.log(outputParams.paramDetail[s].value);
}

The expected outcome of the code should be:

specificationName ["strong", "weak", "energetic"] incident ["123"] groupid ["g1","group1"]

The requirement states that the data type value needs to be an array of strings. The end goal is to categorize values based on their respective field names.

Upon execution, the above code does not generate the intended result when parsed.

Answer №1

Give this a shot

let inputData = { 
    "inputParams" : [
        { "field" : "category", "value" : "fruit"},
        { "field" : "category", "value" : "vegetable"},
        { "field" : "category", "value" : "meat"},
        { "field" : "quantity", "value" : "10"},
        { "field" : "size", "value" : "large"},
        { "field" : "size", "value" : "extra large"}
    ]
};

let outputData = {
    "outputParams" : []
};

for(x=0;x<inputData.inputParams.length;x++){
    existing = false;
    for(y=0;y<outputData.outputParams.length;y++){
        if(outputData.outputParams[y].field == inputData.inputParams[x].field){
            outputData.outputParams[y].value.push(inputData.inputParams[x].value);
            existing = true;
            break;
        }
    }
    if(!existing){
        outputData.outputParams.push({"field" : inputData.inputParams[x].field, "value" : [inputData.inputParams[x].value]});
    }
}

console.log(outputData);

Answer №2

Only when the items are arranged in order, this will function:

var outputparams = { 'paramDetail': [] };
var lastGroup = "";

for ( var n = 0; n < inputParams.inputDetails.length; n++ )
{
     if ( lastGroup !=  inputParams.inputDetails[n].field )
     {
         outputparams.paramDetail.push({ 'field': inputParams.inputDetails[n].field, 'value': [] });
         lastGroup = inputParams.inputDetails[n].field;
     }
     var currentField = outputparams.paramDetail.length -1;

     outputparams.paramDetail[currentField].value.push(inputParams.inputDetails[n].value);

}

This has not been verified yet, but it's the starting point for me.

Answer №3

Utilize this function to handle the inputParams

var processData = function (data) {
    var extractedData = {};
    data.dataDetails.forEach(function (val, index) {
        if (!(val.field in extractedData)) extractedData[val.field] = [];
        extractedData[val.field].push(val.value);
    });
    var result = { paramInfo : [] };
    for (index in extractedData) {
        result.paramInfo.push({
            field: index,
            value: extractedData[index]
        });
    }
    return result;
};

var outputData = processData(inputParams);

Answer №4

Big thanks to Valijon for the amazing help with updating an array value using javascript.

I followed Valijon's advice and made a simple line update in my code. Everything is now running smoothly as desired.

outputParams.paramDetail[tempInd].value.push(arr.jsonList1[index].value);

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

Looping through a series of JavaScript objects in a JSON

I've encountered an issue when trying to run a loop with a JSON query inside it. Here's what my code looks like: for (var i = 0; i < numitems; i++) { var currentitem = items[i]; $.getJSON("http://localhost/items.php", {'itemname&ap ...

Creating a combination of associative keys and numbers within an array using JavaScript

To summarize, my question starts below: I have simply read a JSON file with the following contents: [{"FirstCategory":"Bath","SecondCategory":"Bath Accessories","ThirdCategory":""}, {"FirstCategory":"Bath","SecondCategory":"Faucets","ThirdCategory":""}, ...

What could be causing the sluggishness of this ajax call?

After implementing an ajax function on the page load event, I noticed that there was no record of the call in the server log (which logs all entrance and exit points of all MVC server methods). The request from the JavaScript to the server was taking an un ...

Save pictures in MongoDB using GridFS or BSON format

As a newcomer to MongoDB, I am seeking advice on the best way to store images in the database. Gridfs and BSON seem to be the most common options, but I'm unsure about their respective pros and cons. The main difference I'm aware of is the 16MB s ...

Tips for Choosing a Tab in angular-ui: AngularJS

Is there a way to select the last tab without using ng-repeat? I want to avoid using ng-repeat but still need to select tabs. Any suggestions? If you'd like to see the code in action, you can visit: http://plnkr.co/edit/ZJNaAVDBrbr1JjooVMFj?p=preview ...

Steps to display the leave site prompt during the beforeunload event once a function has finished running

While facing a challenge with executing synchronous Ajax methods in page dismissal events, I discovered that modern browsers no longer support this functionality in the "beforeunload" event. To work around this issue, I implemented a new promise that resol ...

Explain the concept of render hijacking in react technology

After learning about High Order Components (HOC), I came across the concept of render hijacking. Can someone please explain what exactly render hijacking entails? ...

Issue with PassportJs not forwarding users after successful authentication

I'm facing some challenges with implementing Passport for authentication. I have set up my signup strategy in the following way: passport.use('local_signup', new localStrategy({ usernameField: 'username', passwordField:&apo ...

`At a loss: jQuery failing to retrieve JSON data`

I'm having trouble with a basic script that is supposed to fetch data from a JSON feed and display it in an alert. Despite having loaded jQuery correctly and checked for common issues, the code doesn't seem to be working. I am using jQuery and ca ...

Integrating an API with a Discord bot using an embedded link in Discord.js

I am currently in the process of creating a bot that can generate and embed links to display manga titles, tags, and other information based on user-input digits. I have been exploring an API called this and I am eager to learn the most effective method ...

The function document.getElementById(...) is failing to retrieve the text data from the table as expected

Greetings fellow HTML and JavaScript novice! I've got a table with input cells in the bottom row: <table class="convtbl" id="table1"> <tr> <td>Distance 1 (in miles)</td> <td>Time ...

Building an easy-to-use jQuery task list

I'm currently working on a basic to-do list in Javascript, but I've encountered an issue. When I check the checkbox, the style of the adjacent text doesn't change as expected. Instead, it's the heading text that is affected by the chang ...

Error connecting to Firebase Cloud Functions - connection issue

Whenever I call my cloud function, I see the following message in the logs: Function execution took 5910 ms, finished with status: 'connection error'. It seems to be related to promises and returning or !d.exists, but I haven't been able to ...

AngularJS - Organize Item Hierarchy with Separate Containers for Each Group

My goal is to incorporate a $scope variable within an AngularJS controller that has the following structure: $scope.hierarchy = { name: 'bob', selected: true, children: [ { name: 'frank' }, { name: 'spike' ...

Unable to retrieve hours from MongoDB date array

Whenever I fetch data from my NodeJS+MongoDB webservice, I am able to retrieve the date format successfully. However, I am facing an issue when trying to extract hours from it. Here is how the date looks in MongoDB: https://i.stack.imgur.com/qxWGL.png I ...

Is it possible to efficiently transfer a Tensorflow.js Tensor between Node.js processes?

Currently, I am in the process of building an AI model using Tensorflow.js and Node.js. One of the challenges I am facing is handling a large dataset in a streaming manner due to its size being too massive to be stored in memory all at once. This task invo ...

Encountered an error with Aurelia webpack 4 when trying to load a necessary CSS file during runtime

I encountered a unique issue with webpack and aurelia that I can't seem to figure out. After creating a new webpack configuration based on online resources and official documentation, the compilation goes smoothly without any errors. However, during r ...

Encountering difficulties in populating mongoose document following a model query

Hi everyone, this is my first time posting on SO so I'm hoping for some positive outcomes. I've been using Mongoose in a current project without any issues until now. The problem arises when trying to populate object references after querying fo ...

Struggling to retrieve the accurate input value when the browser's return button is clicked?

Having multiple forms created for different conditions, each one submits to a different page. However, when I navigate back from the other page, all my forms display the same values as before. Here's the code snippet: <form action="<?php echo b ...

Working with Firestore database in React Js may result in an infinite loop

I have connected my React JS app to Cloud Firestore and I am facing an issue with displaying the objects in my JavaScript file. Even though I only have one object in Firestore, it seems to be reading in a loop and I can't seem to identify the cause. ...