如何使用 map() 将数组元素分配给不同的变量?

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

澄清我正在使用 React、Node、Postgres、Express。

我有一条 return 行 table 的快速路线,其中每个元素都是不同的列。我想将这些元素中的每一个分配给一个变量,这里是 return 结果的示例:

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

这是我尝试将这些元素映射到单独的变量:

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);
        }
    }

我的目标是每一行都会有不同的结果,并且变量 thickness1 等会根据 returned 的数组有不同的值。在我提供的示例中,我只尝试映射 1 个变量,但即使那样也不起作用。那么我将如何使用 map() 将我的数组元素映射到不同的变量?

我认为您可以使用 .map() 来完成这项任务,但不是在 jsonData 数组本身上,而是在行对象的属性数组上。

// 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);

更多关于 Object.fromEntries() and Object.entries()