You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从飞利浦Hue API返回的JSON结果中提取灯泡名称与state.on状态

解决方法

你拿到的飞利浦Hue API返回结果是以灯泡ID为键的对象结构,不是数组,你可以通过Object.values()获取所有灯泡的配置对象,再遍历提取需要的name和state.on字段。

1. 基础数据提取代码示例

// 假设api返回的结果存在hueLights变量里
const hueLights = { /* 你拿到的JSON数据 */ };

// 提取需要的字段,返回结构为[{id, name, isOn}]的数组
const lightList = Object.entries(hueLights).map(([lightId, lightInfo]) => ({
  id: lightId, // 灯泡的ID,后续要控制灯泡也会用到
  name: lightInfo.name,
  isOn: lightInfo.state.on
}));

执行后得到的lightList结构如下:

[
  { id: "1", name: "TV 2", isOn: false },
  { id: "2", name: "Study", isOn: false }
]

2. React组件中渲染的示例

import { useState, useEffect } from 'react';

function HueLightList() {
  const [lights, setLights] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // 调用Hue API获取数据的逻辑
    fetch('你的Hue API接口地址')
      .then(res => res.json())
      .then(data => {
        const formattedLights = Object.entries(data).map(([id, info]) => ({
          id,
          name: info.name,
          isOn: info.state.on
        }));
        setLights(formattedLights);
        setLoading(false);
      });
  }, []);

  if (loading) return <div>加载中...</div>;

  return (
    <div className="hue-light-list">
      <h2>飞利浦Hue灯泡列表</h2>
      <ul>
        {lights.map(light => (
          <li key={light.id}>
            灯泡名称:{light.name},状态:{light.isOn ? '开启' : '关闭'}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default HueLightList;

内容的提问来源于stack exchange,提问作者William

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:45:03