Reputation: 353
I´m trying to filter the data but i have an array inside an array, and i have no idea how can i get those! Also there is a property called 'toString' and thats might be a problem (function)
const filterteste = this.state.example.changelog.histories.map(item => (
{
id: item.id,
created: item.created,
field: item.items.field,
fromStringprop: item.items.fromString,
toStringprop: item.items.toString,
}
));
Desired Ouput: I´m trying to filter the array soo i have a clean array with the properties i will need
{
created:
id:
field:
fromString:
toString:
}
Upvotes: 1
Views: 3449
Reputation: 889
const filterteste = this.state.example.changelog.histories.map(item => {
//instead of returning a single item, we return an array!
return item.items.map(childItem => {
return {
id: item.id,
created: item.created,
field: childItem.field,
fromStringprop: childItem.fromString,
toStringprop: childItem.toString,
};
});
});
With this code you're mapping the base array elements, and each of these elements is returned as a map of the child elements - does this make sense?
After this you will still have an array, like so:
[
[
//item1,
//item2
],
[
//item3
]
]
At this point we can just call reduce
on this array to get to our expected result...
let resultOfArrayMap = theMapFunctionFromTopOfThePost(baseArray);
const properlyMappedArray = resultOfArrayMap.reduce((arrayBeingBuilt, currValue) => {
return arrayBeingBuilt.concat(...currValue);
}, []);
This starts from an empty array, for each item in our mapped array it concats all of the child items in a new array, then proceeds to the next item and keeps contatenating other items to the array returned by processing the previous element...
It should now look like this:
[
//item1,
//item2,
//item3
]
Upvotes: 2
Reputation: 6587
You could simply filter out them as
const filterteste = this.state.example.changelog.histories.map(item => (
{
id: item.id,
created: item.created,
field: item.items.field,
fromStringprop: item.items.filter((item)=> return item.fromString != null),
toStringprop: item.items.filter((item)=> return item.toString != null)
}
));
Upvotes: 1