[英]Looping through objects in 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;
这对我来说很好,因为你可以看到它正确地循环遍历数组。 你有什么问题?
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": "" } ] } food.design.map((item, i) => console.log(i, item))
下面的方法将返回food.design中的每个对象:
food.design.map(item => { /* do something here */ });
如果您使用的是ECMA Script 6,请使用此脚本
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": ""
}
]
}
const obj = food.design;
for (const key of Object.keys(obj)) {
console.log(key, obj[key]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.