Tips for transferring values from one array to another array using JavaScript

I am attempting to incorporate values from the array below into another array

[
    {"criteriaName": "CRITERIA 1"},
    {"criteriaType": "Dependent"},
    {"table": "Table1"},
    {"column": "Column1"},
    {"joinType": "OR"},
    {"operator": ">="},
    {"valueType": "SQL"},
    {"dataType": "NUMBER"},
    {"format": "Config"},
    {"parameterMandatory": "YES"},
    {"link": "KB"},
    {"sequence": "SEQ1"},
    {"value": "VAL"},
    {"description": "abcde"}
]

From the array above, I am trying to add each value to the nested object below.

Need to add each value from the above array to each model in the array below The target array is as follows.

I attempted to add the values from the above array to the array below

formFields = [
    {
        "title": "Criteria Details",
        "columns": 2,
        "fields": {
            "criteriaName": {
                "type": "text",
                "label": "Criteria Name",
                "id": 'criteriaName',
                "model": "",
                "required": true,
                "show": true,
                "rules": [
                    v => !!v || 'Criteria Name is required',
                ]
            },
            // Additional fields truncated for brevity
        }
    },
    {
        'title': "Notes",
        "columns": 1,
        "fields": {
            "description": {
                "type": "description_notes",
                "label": "Description",
                "id": "description",
                "required": false,
                "model": '',
                "show": true,
            }
        }
    }
]

How can I accomplish this?

Thank you..

Answer №1

I think this is the solution you are looking for:

When iterating through yourFirstArray and formFields, the code below will assign the value of the first key of each object in your first array to the corresponding key in formFields:

yourFirstArray.forEach(function(e){
    formFields.forEach(function(fF){
        var firstKey = Object.keys(e)[0]; // extracting the first key of each object in your first array
        fF[firstKey] = e[firstKey];
    })
})

Answer №2

Resolution:

let newData = modelValues.reduce((accumulator, currentValue) => Object.assign({}, accumulator, currentValue), {});
Object.keys(newData).forEach(property => formFields[property].model = newData[property])

Please take note: modelValues should be your array

However, I suggest restructuring your data like this?

let modelValues = {
    criteriaName: "CRITERIA 1",
    criteriaType: "Dependent",
    table: "Table1",
    column: "Column1",
    joinType: "OR",
    operator: ">=",
    valueType: "SQL",
    dataType: "NUMBER",
    format: "Config",
    parameterMandatory: "YES",
    link: "KB",
    sequence: "SEQ1",
    value: "VAL",
    description: "abcde"
};

and perform the mapping in this manner

Object.keys(modelValues).forEach(property => formFields[property].model = modelValues[property])

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

Having difficulty retrieving the selected value in JSPDF

I am attempting to convert my HTML page into a PDF format by utilizing the following code: domtoimage.toPng(document.getElementById('PrintForm')) .then(function (blob) { var pdf = new jsPDF('p', &apo ...

Tips for referencing a function declared within a prototype

I have been attempting to enhance a web page by adding functionality using a jquery library that lacks documentation. The problem I am encountering is primarily due to my lack of understanding of the jquery plugin model and/or the inner workings of javascr ...

What is the best way to apply identical properties to multiple components at once?

With multiple components like <my-a>, <my-b>, and many more each having a prop: { props: { isDetail: { type: Boolean, default: false, } }, } When creating a form using these components, repeating the prop assignment becom ...

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...

Having trouble mocking Node fs Modules using Sinon

I am facing an issue with mocking the promises methods of the node fs module in my code. When my appData.ts file is executed, it calls the actual fs.promises.mkdir method instead of the mock function defined in \__tests__/appData.test.js. I suspect ...

Error: Missing semicolon at line 1005 in Vue computed function. Vetur is indicating this issue

As a beginner in vue3, I am venturing into building some side projects. However, I keep encountering an error message stating ';' expected.Vetur(1005) when attempting to utilize the computed function. Strangely enough, sometimes the same syntax w ...

The mapDispatchToProps function is failing to work, throwing an error: Uncaught TypeError: _this.props.addCountdown is not a function

Currently, I am facing an issue while working on my first app. The problem arises with a form component that should send an object via an onSubmit handler. onSubmit = (e) => { e.preventDefault(); this.props.onSubmit({ title: ...

Display the personalized list of user items on the MERN dashboard

I'm currently developing a React booking platform that interacts with my backend through a Rest API using axios and redux. My challenge now is to display personalized reservations and rooms for each user on the website. However, I'm facing an iss ...

What is the best way to generate a static header in nextJS?

I am looking to create a static navbar without needing client-side fetching. Currently, I am using Apollo GraphQL and my _app.js file is set up like this: import React from 'react'; import Head from 'next/head'; import { ApolloProvider ...

Data obtained from the server includes JSON objects along with quotes and regular expressions

While analyzing the functionality of a search page server through element inspection, it was observed that requests are sent via POST with JSON parameters. To verify this observation, I recreated the same POST request using Insomnia with identical paramete ...

Issue with jQuery centering in IE browsers with jquery-ui-1.10.3.custom.js and jquery-ui-1.9.2.custom.js not working as expected

Are there any other alternatives you can recommend? Here is the dialog structure: <div id="dialogbox" title="message box"> <p>example content</P> </div> ...

Whenever attempting to update an individual element within an associative array in Vue 3, all values within the array end up being updated simultaneously

In my Vue3 code snippet, I have the following: data: function() { return { testData:[], } }, mounted() { var testObj = { name: 'aniket', lastname: 'mahadik' ...

Learning React: Error - Unable to access the 'data' property when it is null

Currently, I am learning React by following a tutorial available at this link: http://facebook.github.io/react/docs/tutorial.html Specifically, I am focusing on the section related to fetching data from the server, which can be found here: http://facebook ...

Is it possible to reuse variables declared in a Javascript function within the same function?

string empCode = ds.Tables[0].Rows[i]["EMP_CODE"].ToString(); string empName = ds.Tables[0].Rows[i]["EMP_NAME"].ToString(); string gradeCode = ds.Tables[0].Rows[i]["GRADE_CODE"].ToString(); tr = new TableRow(); td = new Ta ...

What is the best way to access the display property of a DOM element?

<html> <style type="text/css"> a { display: none; } </style> <body> <p id="p"> a paragraph </p> <a href="http://www.google.com" id="a">google</a> &l ...

Applying scoped styling in Vue.js renders the SCSS ineffective

My SCSS code works perfectly on a simple page where I apply background-color. However, when I make the file scoped, the SCSS doesn't seem to have any effect. It's important for me to keep this component scoped so that the background-color doesn&a ...

Is there a way to create an input field that accepts only numbers and behaves like a password field simultaneously?

I am attempting to develop an input field for entering a PIN. I would like the PIN to be masked on mobile devices, similar to how passwords are obscured in password input fields. I came across a suggestion on stackoverflow regarding this, but unfortunately ...

Utilizing setInterval Effectively in the Vuex Store

After successfully retrieving data from the API, I encountered compatibility issues with Vue. Check out the console output here: https://i.sstatic.net/eWLW8.png How can I efficiently implement the use of setInterval in the Vuex store without triggering t ...

AngularJS Filtering - content within html elements

I struggle with filtering and would like to create a personalized filter using the following scenario: When I make a call to a service, I receive a JSON object with HTML that is combined with another string, resulting in messy HTML. My goal is to extract ...

Retrieve the attributes of DOM elements following a successful AJAX request

Is there a way to retrieve the video duration using video.duration following my ajax video upload? Despite achieving ajax success, this function continues to return NaN. I have attempted methods such as $.when().then or $.when.done() but with no success. ...