0

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?

0

3 Answers 3

5

Try this:

const Food = FruitsList.map(({name, color}) => {
  return { fruitName: name, fruitColor: color };
})

console.log(Food);
Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly. Thank you so much!. My situation now is I have an array object that I reduced to get only those that matched a value I want. Can reduce be also used along with mapping on one function/method?
0

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);

Comments

-1

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:''}]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.