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?

  • 1
    With the .map function, you want to feed it a function that returns the object you want to be in your new array. arr.map(function(oldElement){ return newElement }). And that leaves you with an array of newElements – TKoL 1 hour ago
4

Try this:

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

console.log(Food);
0

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

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

  • No use in copying other's answers and posting again. – Ramesh 1 hour ago
  • Hi ramesh I think you are wrong please take a look at my answer. It differs from yours – SelakaN 1 hour ago
  • Dont talk like you are the only one who knows javascript in the world. Fairly simple problems can have similar answers. Hope you get that simple logic. What differs from your answer to mine is I have elaborated what I have done and given the OP to something refer with working example. Hope you get that tiny logic. :-) – SelakaN 1 hour ago
  • @SelakaN I'm not understanding the logic of using "let" instead of "const" in your example? – krismeister1993 59 mins ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.