I have the following two interface defined:
interface BarProp {
Item: Foo[];
Date: string;
}
interface Foo {
Name: string;
Date: string;
IsValid: boolean;
}
I'm trying to do two things:
- Clone
BarProp.Itemarray but only with the properties Name and Date - In this cloned array, add a new property if
IsValidistrue
I have implemented the following and it works. But I'm looking for a more elegant solution.
// First create a new array by mapping over `Items` with only `Name` and `Date`
const newItemsArray = BarProp.Items.map((i) => {
return {
Name: i.Name,
Date: i.Date,
};
});
//loop over this new array and conditionally add `New Property`
for (let i = 0; i < newItemsArray.length; i++) {
if (BarProps.Items[i].IsValid) {
newItemsArray[i].NewProperty = "New Property";
}
}
Thanks!
edit:
proposed change:
const newItemsArray = BarProp.Items.map((i, index) => {
if (i.IsValid) {
Name: i.Name,
Date: i.Date,
NewProperty: "NewProperty",
} else {
Name: i.Name,
Date: i.Date,
}
});
propsthe array you need to check for?NewPropertyif IsValid is true. I've updated original post with a proposed change. please have a look.props.Itemsis. Is it a different array? is it just a typo and meant to beBarProp.Items? The proposed change logic is correct anyway, though the syntax is wrong.BarProps.Items.