R
R
RomanSS2017-01-13 15:36:32
JavaScript
RomanSS, 2017-01-13 15:36:32

Sorting data in react + redux?

Please tell me how to solve the problem with unnecessary sorting
1. I pull out the data from the database, they are already sorted in the right way.
The following JSON comes into React:

{"list": 
    {"1003":{"name":"test3"}},
    {"1002":{"name":"test2"}},
    {"1004":{"name":"test4"}},
    {"1001":{"name":"test1"}}
}

2. Saving goes to the Redux store
3. I want to display the data in the component, but it sorts the keys from smallest to largest.
Those. The output to the component is the following data:
{"list": 
    {"1001":{"name":"test1"}},
    {"1002":{"name":"test2"}},
    {"1003":{"name":"test3"}},
    {"1004":{"name":"test4"}}
}

I conclude like this:
{Object.keys(this.props.data.list).map((key, index) => (
   <div>{this.props.data.list[key].name}</div>
))}

I get:
test1
test2
test3
test4
And it should be as it was originally pulled out of the database:
test3
test2
test4
test1
I wanted to first place each object in its own array:
{"list":
[{"1001":{"name":"test1"}} ],
[{"1002":{"name":"test2"}}],
[{"1003":{"name":"test3"}}],
[{"1004":{"name":" test4"}}]
}
But there can be a lot of such data, and it will no longer be possible to access by the key {this.props.data.list['1001'].name}, you will have to constantly run through the entire array in search of this key. How to solve this problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
_
_ _, 2017-01-13
@RomanSS

In point 1, your JSON is not valid. Looks like you meant:

{"list": {
    "1003":{"name":"test3"},
    "1002":{"name":"test2"},
    "1004":{"name":"test4"},
    "1001":{"name":"test1"}
}}

Pass your data as a list, create a separate object with keys and an id array in the reducer to keep order.
{"list": [
    {"1003":{"name":"test3"}},
    {"1002":{"name":"test2"}},
    {"1004":{"name":"test4"}},
    {"1001":{"name":"test1"}}
]}

var indexed = list.reduce((acc, value) => Object.assign(acc, value), {});
   var order = list.map((value) => Object.keys(value)[0]);

This is what the output will look like:
{this.props.data.list.order.forEach((key) => (
   <div>{this.props.data.list.indexed[key].name}</div>
))}

M
Maxim, 2017-01-13
@maxfarseer

You can normalize the data. On this occasion, I think it will be extremely useful for you to watch the second course [EN] from the creator of redux.
ps lesson about normalization , which tells how you can solve your problem, but I think to understand, you need to watch the entire course.
pps useful links:
1) https://rajdee.gitbooks.io/redux-in-russian/conten... (may be translated someday)
2) https://habrahabr.ru/company/hh/blog/ 310524/ (RU)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question