Reputation: 89
Say I have an array like this one I want to loop through it and display the data that's inside the objects, any idea how I can do that?
layout: [
[{
type: 'text',
value: 'abc'
}],
[{
type: 'text',
value: 'def'
}],
[
{
type: 'text',
value: '123'
},
{}
]
]
And here is my loop:
const {layout} = this.state
let rows = []
for (let i = 0; i < layout.length; i++) {
rows.push(<div className="row" key={i}>
</div>);
}
Upvotes: 0
Views: 318
Reputation: 932
I suggest that you use Array.map:
layout.map(row => {
return (
<div>
<input type={row.type} value={row.value} />
</div>
)
})
For a complete example with React, see : https://jsfiddle.net/gbourgin/wu737LLj/
Remark: I don't see why you need an array of array for your layout variable
Upvotes: 0
Reputation:
JS Fiddle Demo React Solution
<div>{(layout).map(function(data){
return(
data.map(function(data){
return(
<div>
{data.type+
"\n"
+data.value
}
</div>
)
})
)
})}</div>
Upvotes: 0
Reputation: 7696
Loop through the array like, and call it by their index like the example below
let layout= [
[
{
type: 'text',
value: 'abc'
}
],
[
{
type: 'text',
value: 'def'
}
],
[
{
type: 'text',
value: '123'
},
{}
]
];
let rows = [];
var div = document.createElement('div');
for (let i = 0; i < layout.length; i++) {
rows.push('<div className="row" key={i}></div>');
var s = '<li>'+layout[i][0].type+': '+layout[i][0].value+'</li>';
document.body.innerHTML +=s;
}
Upvotes: 1
Reputation: 1418
In your for
loop, you get a number to work with. In this case, i
. You can access the contents of i
with layout[i]
. Push that to your rows
object inside the div
, that should work.
Upvotes: 0