我有一个数组
FruitsList = [
{name: 'apple', color: 'red'},
{name: 'grapes', color: 'violet'},
{name:'avocado', color: 'green'}
]
接下来我要填充另一个对象数组
Food = [{fruitName: '', fruitColor:''}]
从先前数组的所有值开始。我尝试映射但失败了。谁能帮助我使用哪种Javascript或Typescript方法?
答案 0 :(得分:4)
尝试一下:
const Food = FruitsList.map(({name, color}) => {
return { fruitName: name, fruitColor: color };
})
console.log(Food);
答案 1 :(得分:0)
你为什么不试试这个
const FruitsList = [{name: 'apple', color: 'red'}, {name: 'grapes', color: 'violet'}, {name:'avocado', color: 'green'}]
const Food = [...FruitsList , {fruitName: '', fruitColor:''}]
答案 2 :(得分:0)
像这样吗?
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);
答案 3 :(得分:0)
您可以使用map()
运算符来完成此操作,并以自己喜欢的方式返回一个新数组。请查找有关javascript地图操作符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);