Dumisani
Dumisani

Reputation: 89

How to loop through an array and display data within the object of that array, in react and javascript

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

Answers (4)

Gr&#233;gory Bourgin
Gr&#233;gory Bourgin

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

user6741062
user6741062

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

Renzo Calla
Renzo Calla

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

Jeff Huijsmans
Jeff Huijsmans

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

Related Questions