提问人:JohnnyPicnic 提问时间:11/16/2023 更新时间:11/16/2023 访问量:41
从对象列表创建嵌套对象
Create nested object from list of objects
问:
是否可以解析此列表并在“RECORD”之后为每个传感器创建一个新的嵌套对象。
{
"TIMESTAMP": "2022-10-21 13:55:00",
"RECORD": "0",
"Sensor1": "1.654",
"Sensor2": "1.176",
"Sensor3": "0.706"
}
结果:
{
"Sensor1": {
"TIMESTAMP": "2022-08-21 13:55:00",
"Value": "1.654"
},
"Sensor2": {
"TIMESTAMP": "2022-08-21 13:55:00",
"Value": "1.176"
},
"Sensor3": {
"TIMESTAMP": "2022-08-21 13:55:00",
"Value": "0.706"
}
}
答:
1赞
Tal Rofe
11/16/2023
#1
只需遍历对象键,忽略 和 键,每个其他键只需使用所需值创建其相应的对象:TIMESTAMP
RECORD
const transform = (input) => {
return Object.keys(input).reduce((accum, inputKey) => {
if (inputKey === 'TIMESTAMP' || inputKey === 'RECORD') {
return accum;
}
return {
...accum,
[inputKey]: {
TIMESTAMP: input.TIMESTAMP,
Value: input[inputKey]
}
};
}, {})
}
// Example
const exampleObject = {
"TIMESTAMP": "2022-10-21 13:55:00",
"RECORD": "0",
"Sensor1": "1.654",
"Sensor2": "1.176",
"Sensor3": "0.706"
};
console.log(transform(exampleObject));
2赞
Sebastian Kaczmarek
11/16/2023
#2
您可以尝试使用 .示例如下:Object.entries(...).reduce(...);
const input = {
"TIMESTAMP": "2022-10-21 13:55:00",
"RECORD": "0",
"Sensor1": "1.654",
"Sensor2": "1.176",
"Sensor3": "0.706"
};
const result = Object.entries(input).reduce((res, [key, val]) => {
if (!key.startsWith("Sensor")) return res;
res[key] = {
TIMESTAMP: input.TIMESTAMP,
Value: val
};
return res;
}, {});
console.log(result);
评论
Object.entries(object).forEach()
Sensor