循环一个物体反应? [英] Loop an object in react?
问题描述
数据:
我有数据有内部数组,我尝试循环默认代码:
I have data that have inside arrays, I try loop by default code:
<div className="loop-container">
{
joblist.map((itemb,index) => (
<div>
</div>
))
}
</div>
我想首先显示那个数组的名称(这是日期)然后显示这个数组包含的内容,但我收到错误:
I want show name of that arrays first, (this is date) then show what this arrays consist, But I get error:
joblist.map不是函数
joblist.map is not a function
推荐答案
我们直接使用 map
, filter
on object,首先我们需要从该对象获取一个数组(属性或属性值)然后我们才可以。
Directly we can't use map
, filter
on object, first we need to get an array (either property or property values) from that object then only we can.
您获得的数据不是数组,因此我们无法直接使用 Array.prototype.map 。您需要做的是首先使用 Object.keys 获取数组中的所有键。一旦你得到数组,使用 map
就可以在 map
里面使用另一个 map
迭代值。
Data that you are getting is not an array, so directly we can't use Array.prototype.map. What you need to do is first use Object.keys to get all the keys in an array. Once you get the array use map
on that and inside map
function body use another map
to iterate the values.
您还可以使用 Object.values 或 Object.entries ,但模式与 Object.keys()。
You can also use Object.values or Object.entries, but pattern will be not same as Object.keys().
像这样写:
<div className="loop-container">
{
Object.entries(joblist).map(([key, value]) => (
<div id={key}>
Date: {key}
{
value.map(el => <div key={el.id}> {el.created_time} </div> )
}
</div>
))
}
</div>
使用 Object.entries :
let obj = {
'key1': [{a:1}, {a:2}, {a:3}],
'key2': [{a:4}, {a:5}, {a:6}],
'key3': [{a:7}, {a:8}, {a:9}]
};
Object.entries(obj).map(([key, value]) => {
console.log('key name = ', key);
value.map(el => {
console.log(el.a);
})
})
使用 Object.keys :
let obj = {
'key1': [{a:1}, {a:2}, {a:3}],
'key2': [{a:4}, {a:5}, {a:6}],
'key3': [{a:7}, {a:8}, {a:9}]
};
Object.keys(obj).map(key => {
console.log('key name = ', key);
obj[key].map(el => {
console.log(el.a);
})
})
使用 Object.values :
let obj = {
'key1': [{a:1}, {a:2}, {a:3}],
'key2': [{a:4}, {a:5}, {a:6}],
'key3': [{a:7}, {a:8}, {a:9}]
};
Object.values(obj).map(value => {
console.log('value = ', JSON.stringify(value));
value.map(el => {
console.log(el.a);
})
})
这篇关于循环一个物体反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!