我有一个遍历数据plotData数组的循环。我用plotData构建了另一个名为visiblePoints的数组。然后,我遍历visiblePoints以构建对象thisRow,然后将thisRow添加到循环外的数组中,该数组称为dataArray

var dataArray = []

for (i = 0; i < plotData.length; i++) {

    // This filters datapoints array into another array
    var visiblePoints = filterPoints(plotData[i].datapoints)

    // Get the string for the thisRow object key name
    var selectedParameter = plotData[i].label

    for (k = 0; k < visiblePoints.length; k++) {
        // Convert visiblePoint first value from ms to date
        var timestamp = new Date(visiblePoints[k][0])

        // Form the thisRow object that will go into dataArray
        // for each loop of visiblePoints
        var thisRow = {}
        thisRow["Time"] = msToTime(timestamp)
        thisRow[selectedParameter] = visiblePoints[k][1]
        dataArray.push(thisRow)
    }
}


简化一下,说每个visisblePoints数组的子数组plotData中只有2个元素,就像这样(每个plotData数组可以有很多visiblePoints,但我简化为每个2个):

plotData[0].visiblePoints = [[00:00:01, 1], [00:00:02, 4] ...]
plotData[1].visiblePoints = [[00:00:01, 27], [00:00:02, 31] ...]


plotData在控制台上如下所示:

javascript - 检查对象是否具有键,如果有,则向该对象添加新的key:值-LMLPHP

visiblePoints循环的k数组是从plotData.datapoints派生的,看起来像:

javascript - 检查对象是否具有键,如果有,则向该对象添加新的key:值-LMLPHP

其中visiblePoints[n][0]是一个以毫秒为单位的值(我将其转换为秒),而visiblePoints[n][1]只是一个浮点值。

visiblePoints =
[0, 0.0500466109191]
[100, 0.0548114598135]
[200, 0.0550143573252]
[300, 0.0549408536766]
[400, 0.0546117305419]
[... repeat 300+ times...]


遍历plotData[i]visiblePoints[k]之后,我得到:

dataArray = [
    {
        "Time": 00:00:01,
        "foo": 1
    },
    {
        "Time": 00:00:01,
        "bar": 27
    },
    {
        "Time": 00:00:02,
        "foo": 4
    },
    {
        "Time": 00:00:02,
        "bar": 31
    },
]


当我打算结束时:

dataArray = [
    {
        "Time": 00:00:01,
        "foo": 1,
        "bar": 27
    },
    {
        "Time": 00:00:02,
        "foo": 4,
        "bar": 31
    }
]


我认为在循环k中,我需要遍历dataArray,检查那里的所有对象,以查看是否存在与Time匹配的thisRow["Time"] = msToTime(timestamp)键,如果是,则在其中添加thisRow[selectedParameter] = visiblePoints[k][1],如果不匹配,创建一个新对象。

问题:


我不确定如何在JS中进行检查(我在Python上有更多经验,但在那方面却不多
好像我正在做很多循环。我不确定再添加一个遍历整个dataArray并检查所有对象以查看其中是否存在键是最好的解决方案。 plotData.visiblePoints数组的长度可以超过500。


[编辑]简化了问题。添加了图片示例。添加了k数组的文本示例。

最佳答案

您可以构建一个键入分组的对象-在这种情况下为时间戳。这样一来,您无需搜索数组即可随机访问所需的项目。完成后,对象的Object.values将是分组对象的数组:



let plotData = [
    {
        label: 'foo',
        visiblePoints: [[`00:00:01`, 1], [`00:00:02`, 4]]
    },
    {
        label: 'bar',
        visiblePoints: [[`00:00:01`, 27], [`00:00:02`, 31]]
    }
]

let groups = plotData.reduce((obj, {label, visiblePoints}) => {
    visiblePoints.forEach(([time, val]) => {
        if(!obj[time]) obj[time] = {Time: time}  // if we haven't seen this time make a new object at that key
        obj[time][label] = val
    })
    return obj
},   {})
console.log(Object.values(groups))

09-25 15:47