hi everyone i have a question about react native. How do I merge two states into one? if for example I have:
this.state.post=[{"author": "167635", "authorName": "willy il coyote", "comment": undefined}, {"author": "167635", "authorName": "willy il coyote", "comment": undefined}, {"author": "139594", "authorName": "ao", "comment": "ccc "}, {"author": "142494", "authorName": "Ao", "comment": "Ravioli "},{"author": "5555", "authorName": "Mark", "comment": undefined},{"author": "7777", "authorName": "Jenny", "comment": undefined},{"author": "2222", "authorName": "Heley", "comment": undefined},{"author": "0000", "authorName": "Pott", "comment": undefined},{"author": "6666", "authorName": "Helen", "comment": undefined},{"author": "1234", "authorName": "Gess", "comment": undefined}]
this.state.post_update=[{"author": "uuuu", "authorName": "xxx", "comment": undefined}, {"author": "777", "authorName": "hhhhh", "comment": undefined}]
now I want to create an array of size 10 which contains the union of post_update and post. But I want to show first the post_update posts and then in the remaining places I put post_update. So i want this output:
this.state.new_state=[{"author": "uuuu", "authorName": "xxx", "comment": undefined}, {"author": "777", "authorName": "hhhhh", "comment": undefined},{"author": "167635", "authorName": "willy il coyote", "comment": undefined}, {"author": "167635", "authorName": "willy il coyote", "comment": undefined}, {"author": "139594", "authorName": "ao", "comment": "ccc "}, {"author": "142494", "authorName": "Ao", "comment": "Ravioli "},{"author": "5555", "authorName": "Mark", "comment": undefined},{"author": "7777", "authorName": "Jenny", "comment": undefined},{"author": "2222", "authorName": "Heley", "comment": undefined},{"author": "0000", "authorName": "Pott", "comment": undefined}]
How can i do?
CodePudding user response:
Merge using the spread operator.
const postMerge =[...post_update, ...post];
const post=[{"author": "167635", "authorName": "willy il coyote", "comment": undefined}, {"author": "167635", "authorName": "willy il coyote", "comment": undefined}, {"author": "139594", "authorName": "ao", "comment": "ccc "}, {"author": "142494", "authorName": "Ao", "comment": "Ravioli "},{"author": "5555", "authorName": "Mark", "comment": undefined},{"author": "7777", "authorName": "Jenny", "comment": undefined},{"author": "2222", "authorName": "Heley", "comment": undefined},{"author": "0000", "authorName": "Pott", "comment": undefined},{"author": "6666", "authorName": "Helen", "comment": undefined},{"author": "1234", "authorName": "Gess", "comment": undefined}];
const post_update=[{"author": "uuuu", "authorName": "xxx", "comment": undefined}, {"author": "777", "authorName": "hhhhh", "comment": undefined}];
const postMerge =[...post_update, ...post];
console.log(postMerge);