Home > Blockchain >  How do I use map() to assign array elements to different variables?
How do I use map() to assign array elements to different variables?

Time:03-26

to clarify I'm using React, Node, Postgres, Express.

I have an express route that return a table row, where each element is a different column. I want to assign each of these elements to a variable, here is an example of how the return results will look like:

Object { test1_id: "4", parts_id: 26, parts_material: "Plexiglass", … }
​
parts_id: 26
​
parts_material: "Plexiglass"
​​
parts_material_length: "49.78"
​​
parts_material_thickness: "1.86"
​​
parts_material_width: "24.96"
​​
parts_produced: 5
​​
test1_id: "4"
​​
workorder_id: 2
​​
workorder_total: 76

And here is my attempt at mapping these elements to seperate variables:

let thickness1 = 0;
    let width1 = 0;
    let length1 = 0;
    let partNeeded = 0;

// Material requirements calculation
    const getReq = async (id) => {
        try {
            console.log(materials);

            const response = await fetch(`http://localhost:5000/materials/${id}`, [id])
            const jsonData = await response.json();

            jsonData.map(x => x.parts_material_thickness = thickness1);

            console.log(jsonData)
            console.log('ID is: ',id)
            //console.log();
            //console.log('Thickness is: ', thickness1);


        } catch (err) {
            console.log(err.message);
        }
    }

My goal here is that every row will have different results, and the variables thickness1, etc will have different values depending on the array that was returned. In the example I provided I only tried mapping 1 variable, but even that isn't working. So how would I go using map() to map my array elements to different variables?

CodePudding user response:

I think you can use .map() for this task, but not on the jsonData array itself, but on the array of the properties of your row object.

// This assumes that:
// 1. The order of values in jsonData matches
//    with the order of properties in the row object.
// 2. The row object already has properties (has columns)
//    but no values yet (undefined or null)
const assignedRowEntries = Object.entries(rowObject).map(
    [key, value], index => [key, jsonData[index]]
);

console.log(assignedRowEntries);
// assignedRowEntries should look like this:
// [
//    [parts_id, value1],
//    [parts_material, value2],
//    ...
//    [workorder_total, value3]
// ]

// This is what you needed
const assignedRowObject = Object.fromEntries(assignedRowEntries);

More about Object.fromEntries() and Object.entries().

CodePudding user response:

.map() returns a new array, so you need to assign it to a variable:

jsonData = jsonData.map(x => x.parts_material_thickness = thickness1);
  • Related