我知道这是我应该知道的东西,但是我很难弄清楚。
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;
答案 0 :(得分:0)
这对我来说很好,因为您可以看到它正确地遍历了数组。你怎么了?
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))
答案 1 :(得分:0)
下面的方法将返回 food.design 中的每个对象:
food.design.map(item => { /* do something here */ });
答案 2 :(得分:0)
如果您使用的是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]);
}