我想从我从API获取的数据中获取所有单个组件。但是来自API的数据是这样的:
{
"1":{
"id":1,
"name":"Burger",
"price":8.99,
"quantity":"2",
"attributes":[
],
"conditions":[
]
},
"2":{
"id":2,
"name":"Poutine",
"price":9.99,
"quantity":"2",
"attributes":[
],
"conditions":[
]
}
}
如果我在此数组上使用map函数,则表示map函数不存在。而且我没有可以使用的通用数组名称来获取所有数据。我是否应该使用for循环来遍历所有单个产品?
答案 0 :(得分:1)
这是一个对象,但看起来属性“键”都是序数数字。
如果您不关心这些键,则只需在其上调用Object.values()
即可返回一个值数组,map函数将在该数组上工作。
var obj ={
"1":{
"id":1,
"name":"Burger",
"price":8.99,
"quantity":"2",
"attributes":[
],
"conditions":[
]
},
"2":{
"id":2,
"name":"Poutine",
"price":9.99,
"quantity":"2",
"attributes":[
],
"conditions":[
]
}
};
var justTheValues = Object.values(obj);
//get the list of just the ids
var idList = justTheValues.map(function(item){
return item.id;
});
答案 1 :(得分:0)
请Object.entries(data).map(item => item[1]).map()
答案 2 :(得分:0)
您可以使用lodash的地图
import _ from 'lodash'
let data ={
"1":{
"id":1,
"name":"Burger",
"price":8.99,
"quantity":"2",
"attributes":[
],
"conditions":[
]
},
"2":{
"id":2,
"name":"Poutine",
"price":9.99,
"quantity":"2",
"attributes":[
],
"conditions":[
]
}
};
_.map(data,( item) => console.log(item))
答案 3 :(得分:0)
在父组件中,使用for in循环映射值以生成组件数组。
let arr = [];
for(let i in obj){
let item = obj[i]
arr.push(<DataComp {...item}/>)
}
这里有一个有效的代码段,因此您可以查看一下。
class DataComp extends React.Component {
render(){
//here you can setup your child component however you need
return (<div>Name: {this.props.name}, Price: {this.props.price}</div>);
}
}
class App extends React.Component {
render(){
let obj = {
"1":{
"id":1,
"name":"Burger",
"price":8.99,
"quantity":"2",
"attributes":[
],
"conditions":[
]
},
"2":{
"id":2,
"name":"Poutine",
"price":9.99,
"quantity":"2",
"attributes":[
],
"conditions":[
]
}
};
let arr = [];
for(let i in obj){
let item = obj[i]
arr.push(<DataComp {...item}/>)
}
return (<div>{arr}</div>);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>