So basically here is what I have, which works as intended -
let newList: any[] = [];
for (let stuff of this.Stuff) {
newList = newList.concat(stuff.food);
}
So basically Stuff is an array of objects where each object has a property that is another object called food. I want to go through this array of Stuff and create a new array with each instance of food within it.
I don't think the way I have done it is bad, I'm just wondering for my own curiosity how someone would have done this without the for loop.
Cheers.
You're looking for the map
method :
const newList = this.Stuff.map(stuff => stuff.food);
You shouldn't need to use continuous reassignment to a variable, and it's certainly not functional :-) Also, using concat
repeatedly is pretty inefficient, you'd better have used push
within the for…of
loop. But map
is still simpler and better.
Try this approach as well using reduce method
var arr = [[1,2,3],[4,5,6],[7,8,9]]; var output = arr.reduce( function ( prev, curr ){ return prev.concat( curr ) } ); console.log(output);
You can express this nicely with an added functional primitive
const prop = x => y => y[x];
const newList = this.Stuff.map(prop('food'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.