reactjs - 条件满足时在循环内循环应返回 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))
}
}
))
我期望最终阵列应该是具有配置和传感器阵列的单个阵列,但我收到两个不同的阵列。
解决方案
我猜您希望合并您的对象值,而不是单独将它们推送到您可以使用扩展运算符语法的数组中
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)
推荐阅读
- php - 如果@include 中存在变量,则检查刀片
- cron - ngx-cron-editor 错误 TS1086 - 无法在环境上下文中声明访问器
- python - Pytest monkeypatch 未正确归因于属性
- docker - Kubernetes + Istio 入口网关端口
- swift - 带有 NSTokenFieldCell 的 MacOS Swift NSTableView 跟踪拖动从哪一列开始
- javascript - 悬停时同时显示下拉菜单
- bash - 将 bash shell 脚本的输出作为 shell 命令运行?
- c# - Resource Dictionary DataTemplate does not recognise the x:Name
- php - 遍历这个多维数组并在 Laravel Blade 中显示为项目列表
- flutter - Chrome 或 web 在 Flutter 2.05 中无法正常工作,不断给出如此多的错误并且无法编译