Srinivas
Srinivas

Reputation: 1556

How to display object properties dynamically in reactjs list view

Iam trying to render a list view from json object. Here object properties are dynamic we cant predict everytime it loads what kind of properties it might get.

Scenario1:

let foo = {
    bar: 'Hello World',
    baz: 'How are you doing?',
    last: 'Quite alright'
};

Scenario2:

let foo = {
    abc: '123',
    xyz: 'timestamp string format'
};

I tried this with plain javascript, but how to make this with reactjs list view? will foo.map() works or is there any alternative approach for this ?

for (var key in foo) {
  console.log(key+' : '+foo[key]);
}

View to achieve(Table)

bar  | helloworld
baz  | how are u doing
last | Quite alright

Any suggestions?

Thanks

Upvotes: 0

Views: 658

Answers (3)

Shakil
Shakil

Reputation: 4630

There may have multiple way to do that. I think this is the most straight forward one.

 <ul className="my-list">
      {Object.values(foo).map((myFoo, i) =>
         <li key={i}>{myFoo.key} | {myFoo.value}</li>
      )}
 </ul>

Upvotes: 0

AlphaD
AlphaD

Reputation: 126

The way I would recommend is to use Object.keys:

<ul>
  {Object.keys(foo).map(key => 
    <li key={key}>{key} | {foo[key]}</li>
  )}
</ul>

This allows you to do what you want without having to manipulate your current object.

Upvotes: 0

nnyby
nnyby

Reputation: 4668

You can find this in the React docs on Lists and Keys.

const listItems = Object.values(foo).map((x, i) =>
  <li key={i}>{x}</li>
);

ReactDOM.render(
  <ul>{listItems}</ul>,
  document.getElementById('root')
);

Upvotes: 1

Related Questions