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

Ways to set the base URL on the development server for a call to react-scripts start

I am facing an issue with configuring my primary PHP server to run the ReactJS dev server created using yarn start within a directory named /reactive on the PHP site (using nginx proxy_pass). The problem is that I cannot set the root of the node server to ...

Navigating the intricacies of sub-State mapping in Nuxtjs

I have set up a state called ~/store/modules/general/index.js Within this state, there are Actions named get_info and get_pages, as well as states named info and pages. When I use ...mapActions({ getInfo: 'modules/general/get_info' getPages: ...

Issues surrounding the determination of CSS attribute value using .css() function within a variable

I have been working on a function to change the color of a span dynamically from black to a randomly selected color from a predefined list. However, I am encountering an issue with the .css("color", variableName) part of my code and suspect that my synta ...

"Resetting the state of a form in AngularJS2: A step-by

Looking to reset the form state from dirty/touched in angular? I am currently delving into the world of angular2 and working on a form with validation. In my journey, I came across this code snippet: <form *ngIf="booleanFlag">..</form> This ...

Having trouble sending a POST request to an Endpoint with Formidable and Request

I am encountering an issue while attempting a basic file upload to a REST endpoint using Node. The error that keeps appearing is: TypeError: Cannot read property 'hasOwnProperty' of null Below is my form setup: <form action="/upload4" me ...

Could use some help with configuring express routes with parameters

Greetings! I am new to working with Express and I am currently in the process of creating a portfolio website. In my project, I have a Pug file named project.pug which includes HTML content that should dynamically render based on the ID of each project sto ...

The AJAX response containing jQuery is failing to produce any visible changes

On Page 1 of my website, there is a form that, upon submission, loads Page 2 using jQuery. This process involves calling a PHP page and displaying the output on Page 1 without actually reloading the entire page. To maintain security, I have set up session ...

Replace the JS function in the bundle with a new custom function

I have compiled my AngularJS website using webpack. While in the Chrome console, I am trying to override a function within the controller of a particular directive. Is this achievable? ...

Error: The react.js application is unable to access the property 'classList' of a null object

I've encountered a bug that's been causing me some trouble. Every time I try to run my react application, I keep getting an error message that reads TypeError: Cannot read property 'classList' of null. As someone who is new to react, I& ...

Enzyme's simulate() failing to produce expected results with onChange event

I am facing an issue with a component and its related tests: import React from 'react'; import PropTypes from 'prop-types'; function SubList (props) { var subways = ['', '1', '2', '3', & ...

Struggling with css margins and div image constraints, seeking guidance and tips for resolution

Struggling with creating a dynamic gallery that works smoothly in jsfiddle but encounters multiple issues when integrated into WordPress. The main problem is the excessive stretching of margins between image titles and meta-data, leading to misalignment an ...

Using Vue.js to toggle rendering based on checkbox selection

Struggling to conditionally render form elements in Vue based on user input. I can do this with VanillaJS or jQuery, but struggling to implement it with Vue's built-in conditional directives. Using single-file components with the webpack template from ...

Embed a function within a string literal and pass it to another component

Is there a way to pass a function defined in actions to an element? Reducer case 'UPDATE_HEADER': return Object.assign({}, state, { headerChildren: state.headerChildren.concat([action.child]) }); Action.js export const deleteH ...

The importance of context visibility for functions in JavaScript within a React.js environment

Why is it that the react state is visible in the function handleFinishChange, but cannot be seen in validationFinishTime? Both are passed to the component InputFieldForm. When executing this code, an error of Uncaught TypeError: Cannot read property ' ...

What is the best way to implement a sub-menu using jQuery?

After successfully implementing a hover effect on my menu item using CSS, I am now struggling to make the sub-menu appear below the menu item upon hovering. Despite my efforts to search for jQuery solutions online, I have not been successful. Are there a ...

The click event in jQuery is being blocked by the use of "display:none

Currently, I have implemented a search box feature with search suggestions: <input id="searchBar" /> <div id="searchSuggestion"></div> The searchSuggestion div is dynamically updated using jQuery ajax whenever an input is entered (imple ...

The system is currently unable to find the specified element

I am facing an issue trying to locate a button that is defined under a specific class using XPATH. The error message "Unable to locate element" keeps popping up. Here are the details of the class: <div class="aui-button-holder inputBtn" id="aui_3_4_0_1 ...

Updating data on the next page with the ID from the previous page in Ionic

In my Ionic application with a SQLite database, I need to transfer data from the "Data Form" page to the "Add More Info" page using the same ID. This data needs to be loaded on the "Add More Info" page before any controller is executed. Once on the "Add Mo ...

Animating a Canvas to Follow Mouse Coordinates

I am looking for a way to animate a circle moving towards specific coordinates, similar to the game . I have attempted using the jquery animate() function, but it is too slow due to the constant updating of the target coordinates. Is there a faster metho ...

How to Override package.json Scripts in NPM

Is it possible to modify package.json scripts without changing the original file? I need to customize the memory allocation for a specific step, but altering the package.json will affect everyone. For example, our current script is: "script": { "dev": ...