I have an array
FruitsList = [
{name: 'apple', color: 'red'},
{name: 'grapes', color: 'violet'},
{name:'avocado', color: 'green'}
]
Next I want to fill another array of objects
Food = [{fruitName: '', fruitColor:''}]
from all the values of the previous array. I tried mapping but failed. Can anyone help what approach in Javascript or Typescript I can use?
Try this:
const Food = FruitsList.map(({name, color}) => {
return { fruitName: name, fruitColor: color };
})
console.log(Food);
why won't you try this
const FruitsList = [{name: 'apple', color: 'red'}, {name: 'grapes', color: 'violet'}, {name:'avocado', color: 'green'}]
const Food = [...FruitsList , {fruitName: '', fruitColor:''}]
Something like this?
food = [];
var list = [
{ name: "apple", color: "red" },
{ name: "grapes", color: "violet" },
{ name: "avocado", color: "green" }
];
list.forEach(function(element) {
food.push({ fruitName: element.name, fruitColor: element.color });
});
console.log(food);
You can use the map()
operator to accomplish this and return a new array the way you like. Please find more about the javascript map operator here
FruitsList = [{name: 'apple', color: 'red'}, {name: 'grapes', color: 'violet'}, {name:'avocado', color: 'green'}] let Food = FruitsList.map(({name, color}) => { return { fruitName: name, fruitColor: color }; }) console.log(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.