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

时间:2018-12-06 17:55:03

标签: javascript arrays javascript-objects

我有一个遍历数据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,但我m简化为每个2):

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

plotData在控制台上看起来像这样:

enter image description here

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

enter image description here

其中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],否则请创建一个新对象。

问题:

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

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

3 个答案:

答案 0 :(得分:1)

您可以使用Map或哈希表,以同时保留对对象的引用。

var map = new Map,
    timestamp,
    row;

// later in loop
timestamp = msToTime(new Date(visiblePoints[k][0]));
row = map.get(timestamp);
if (!row) {
    map.set(timestamp, row = { Time: timestamp });
}
row[selectedParameter] = visiblePoints[k][1];

// at the end assign the array
dataArray = Array.from(map.values())

答案 1 :(得分:1)

您可以构建一个键入分组的对象-在这种情况下为时间戳。这样一来,您无需搜索数组即可随机访问所需的项目。完成操作后,对象的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))

答案 2 :(得分:0)

您可以通过调用Object方法来确定hasOwnProperty是否具有特定的密钥。

const obj = {
  "bar": [1,2,3],
  "foo": "im foo"
};

console.log(obj.hasOwnProperty("bar"))
console.log(obj.hasOwnProperty("bar2"))

您需要遵循这种模式。

var dataArray = []

for (i = 0; i < 1; i++) {

    for (k = 0; k < 2; k++) {
    
        thisRow = {};
        thisRow["Time"] = k+1 * i+1
        thisRow["foo"] = i+1
        thisRow["var"] = k+1
        dataArray.push(thisRow)
    }
}

console.log(dataArray)