0

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>);
}
0

4 Answers 4

1

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;
         }

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, layout[i][0].type simple logic is what I needed
0

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.

Comments

0

JS Fiddle Demo React Solution

<div>{(layout).map(function(data){ return( data.map(function(data){ return( <div> {data.type+ "\n"
+data.value } </div> ) }) ) })}</div>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.