首页 > 解决方案 > 在javascript中循环对象

问题描述

我知道这是我应该知道的,但我很难弄清楚。

const food = {
  "design": [
    {
      "forTemperature": {
        "high": "100",
        "low": "70"
      },
      "productURL": "",
      "imageURL": ""
    },
    {
      "forTemperature": {
        "high": "80",
        "low": "65"
      },
      "productURL": "",
      "imageURL": ""
    },
    {
      "forTemperature": {
        "high": "75",
        "low": "65"
      },
      "productURL": "",
      "imageURL": ""
    },
    {
      "forTemperature": {
        "high": "67",
        "low": "60"
      },
      "productURL": "",
      "imageURL": ""
    }
  ]
}

我拥有的基本 json 文件,数组中的对象,但执行以下操作:

food.design.map((item, i) => i

对我不起作用。

我需要采取什么方法?


import food from "./apiDesign.json";


const New = props => {

  const [food, setFood] = useState([]);

  useEffect(() => {

    const fetchAPI = async e => {
      const designer = await food;
      setFood(designer);
    };

    fetchAPI();

  }, [])

  const stuff = () => {
    return loop // I was trying to loop it in here
  };

  return (
    {stuff}
  )
}

export default New;

标签: javascriptarraysjsonjavascript-objects

解决方案


下面的方法将返回food.design内部的每个对象:

food.design.map(item => { /* do something here */ });

推荐阅读