首页 > 解决方案 > 我正在尝试从对象数组中检索数字数组

问题描述

当我运行 generateData() 函数时,它返回一个 NaN 数组。

function generateData(name) {
    var arr = [];
    var t;
    const x = name;
    for (i = 0; i < data.data.length; i++) {
        t = Number(data.data[i].x)
        arr.push(t);
    }
    return arr;
}

物体 -

{data: Array(15), errors: Array(1), meta: {…}}
data: Array(15)
0: {Node no.: 1, CenterA: 0, LeftA: 4.36, RightA: 3.86, RoadA: 1.14, …}
1: {Node no.: 2, CenterA: 5, LeftA: 1.71, RightA: 1.57, RoadA: 2.07, …}
2: {Node no.: 3, CenterA: 0, LeftA: 3.79, RightA: 4.79, RoadA: 2.86, …}
3: {Node no.: 4, CenterA: 4.64, LeftA: 5.36, RightA: 2.29, RoadA: 2.5, …}
4: {Node no.: 5, CenterA: 0, LeftA: 4.21, RightA: 4.43, RoadA: 2.14, …}
5: {Node no.: 6, CenterA: 4.86, LeftA: 3.21, RightA: 1.43, RoadA: 2.21, …}
6: {Node no.: 7, CenterA: 0, LeftA: 5.79, RightA: 5.5, RoadA: 2.36, …}
7: {Node no.: 8, CenterA: 5.86, LeftA: 2.71, RightA: 3.21, RoadA: 2.93, …}
8: {Node no.: 9, CenterA: 0, LeftA: 5.29, RightA: 6.64, RoadA: 2.64, …}
9: {Node no.: 10, CenterA: 5.57, LeftA: 1.36, RightA: 2.86, RoadA: 2.07, …}
10: {Node no.: 11, CenterA: 0, LeftA: 5.43, RightA: 5.29, RoadA: 1.5, …}
11: {Node no.: 12, CenterA: 4.43, LeftA: 2.79, RightA: 4.21, RoadA: 3.21, …}
12: {Node no.: 13, CenterA: 0, LeftA: 4.79, RightA: 5.43, RoadA: 2.29, …}
13: {Node no.: 14, CenterA: 0, LeftA: 4.57, RightA: 3.64, RoadA: 2.71, …}
14: {Node no.: null}

我需要一个数组,其中包含不同列的所有条目,例如 RightA、CenterA 等。我在代码中使用 Number() 函数将条目转换为数字,但它仍然不起作用

标签: javascriptarraysobjectecmascript-6

解决方案


使用计算的属性名称:

t = Number(data.data[i][x])

推荐阅读