This is a translate of the original question, sorry for the english
I'm creating a filter for the notifications of an app I'm working on, the app is in react, the thing is this, I'm trying to use filter and map, but for some reason, I think it's probably some syntax error on my part, it does not do the filtering part, in the data I receive there is a value called status, if this is completed I want it to be removed from the new array.
status is located in notifications.data.status I put below the way I receive the data
It only does the mapping, I have to use Object.keys, because of the rest it gives me a compiled error, thank you very much
<GlobalNotifications id="GlobalNotifications">
{/* {console.log(Object.keys(notifications.data).filter(notification => notification.status !== 'completed'))} */}
{console.log(Object.values(notifications.data))}
{Object.keys(notifications.data)
.filter(notification => notification.status !== 'completed')
.map(key => (
<NotificationItem
id={key}
key={key}
data={notifications.data[key]}
openHistory={openHistory === key}
callbackOpenHistory={onOpenHistory}
/>
))}
</GlobalNotifications>
CodePudding user response:
I suggest to remove the rxjs tag as your question is related to JavaScript higher order functions on arrays but has nothing to do with rxjs
CodePudding user response:
Your notifications.data is already an array, so you don't need to use Object.keys() to return an array.
filteredArray = data
.filter((notification) => notification.status === "accepted")
Then map the returned filtered array (I used 'accepted' as it gave more elements to play with) based on each item. .map((item) => { the brackets for your code and return(make sure to return your jsx within these parentheses)})
It is best to use a unique key when making a list, so I chose to use your item._id for the key. Sample Data and code below followed by output
import "./styles.css";
let data = [
{
status: "completed",
events: [],
_id: 1
},
{
status: "accepted",
events: [],
_id: 2
},
{
status: "accepted",
events: [],
_id: 3
},
{
status: "accepted",
events: [],
_id: 4
},
{
status: "accepted",
events: [],
_id: 5
},
{
status: "accepted",
events: [],
_id: 6
},
{
status: "accepted",
events: [],
_id: 7
},
{
status: "accepted",
events: [],
_id: 8
},
{
status: "accepted",
events: [],
_id: 9
},
{
status: "accepted",
events: [],
_id: 10
}
];
const filteredArray = data
.filter((notification) => notification.status === "accepted")
.map((item) => {
let key = item._id;
return (
<div key={key}>
id: {key}; status: {item.status}
</div>
);
});
Output:
id: 2; status: accepted
id: 3; status: accepted
id: 4; status: accepted
id: 5; status: accepted
id: 6; status: accepted
id: 7; status: accepted
id: 8; status: accepted
id: 9; status: accepted
id: 10; status: accepted