首页 > 解决方案 > 条件满足时在循环内循环应返回 newsingleArray

问题描述

我有两个循环,当满足条件时我想返回单个数组。我的配置数组如下

"configuration": [
            {
               "position": "O",
                "side": "L",
                "type": 21,
                "wheel": 1,
                "wheels": 20
            },
            {
                "position": "I",
                "side": "L",
                "type": 21,
                "wheel": 2,
                "wheels": 20
            },
]

我的传感器阵列如下

“Sensor”: [
            {
                "pressure": 8126,
                "sub_item": "1",
                "temp": 16,
                "time": 1572243074,
            },
            {
                "pressure": 8205,
                "sub_item": "10",
                "temp": 18.3,
                "time": 1572243092,
            },
]

我正在从配置数组中循环遍历传感器数组并在此处设置条件

let finalarray = []
configuration.forEach((e1) => sensorData.forEach((e2) => {
  if (e1.wheel == e2.sub_item) {
    finalarray.push(e1)
    finalarray.push(e2)
    console.log(JSON.stringify(finalarray))
  }
}
))

我期望最终阵列应该是具有配置和传感器阵列的单个阵列,但我收到两个不同的阵列。

标签: reactjsloopsforeach

解决方案


我猜您希望合并您的对象值,而不是单独将它们推送到您可以使用扩展运算符语法的数组中

const configuration = [
            {
               "position": "O",
                "side": "L",
                "type": 21,
                "wheel": 1,
                "wheels": 20
            },
            {
                "position": "I",
                "side": "L",
                "type": 21,
                "wheel": 2,
                "wheels": 20
            },
    ] 
    const sensorData = [
            {
                "pressure": 8126,
                "sub_item": "1",
                "temp": 16,
                "time": 1572243074,
            },
            {
                "pressure": 8205,
                "sub_item": "10",
                "temp": 18.3,
                "time": 1572243092,
            },
    ]
    let finalarray = []
    configuration.forEach((e1) => sensorData.forEach((e2) => {
      if (e1.wheel == e2.sub_item) {
        finalarray.push({...e1, ...e2})
      }
    }))
    console.log(finalarray)


推荐阅读