从对象列表创建嵌套对象

Create nested object from list of objects

提问人:JohnnyPicnic 提问时间:11/16/2023 更新时间:11/16/2023 访问量:41

问:

是否可以解析此列表并在“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"
    }
}
JavaScript 对象 嵌套

评论

1赞 Barmar 11/16/2023
是的,这是可能的。使用并检查密钥是否以 开头。如果是这样,请在结果中创建相应的属性。Object.entries(object).forEach()Sensor
0赞 Barmar 11/16/2023
请展示您尝试过的内容。我们会帮你修复它,我们不会为你写。

答:

1赞 Tal Rofe 11/16/2023 #1

只需遍历对象键,忽略 和 键,每个其他键只需使用所需值创建其相应的对象:TIMESTAMPRECORD

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);