Is it better to have data arranged with an array of objects or an object of objects for use in React?



I am structuring data to be used later to hydrate a table in react, where the data will change dynamically through WebSocket calls. Currently I have an array of objects:

Array(2) [Object, Object]
    [[Prototype]]: Array(0)
    length: 2
    0: Object {name: "pizza", poolsCount: 2, pools: Array(2)}
    1: Object {name: "apple", poolsCount: 3, pools: Array(3)}
    __proto__: Array(0)

I can convert the arrays to objects using result = Object.assign({}, result1);:

Object {0: Object, 1: Object}
    [[Prototype]]: Object
    0: Object {name: "pizza", poolsCount: 2, pools: Array(2)}
    1: Object {name: "apple", poolsCount: 3, pools: Array(3)}
    __proto__: Object

With that data, and once I get the React UI setup, I will want to each pools object’s properties to be displayed in its own column:

enter image description here

Which is more convenient and recommended for use in my react application?


Actually, that depends on the application’s structure and what is that for.

But personally, I’d like to go with the first approach with Object array as it’s very convenient for displaying data using map which is very often used to display collection data.

And you know, table is an array of rows and each row represent one item in the array so it’s very useful to go with array.

One more thing is that if you convert the array to object, you don’t know the original sequence of the array so you cannot sort it when it comes to be done.

I suggest using array instead of Object.

Answered By – Alan Zhu

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More