0

My object look something like this.

var fruits = [
    {
        name: 'apple',
        color: 'golden'
    },
    {
        name: 'pear',
        color: 'green'
    },
    {
        name: 'mango',
        color: 'yellow'
    }
]

Now what i want is an array of the names of the fruit from the fruit object

console.log(getFruitNames(fruits)) //['apple','pear','mango']
1
  • What have you tried so far to solve this? The problem you describe is trivial and I'd expect you to be able to find at least a working solution. Commented Sep 26, 2021 at 11:34

2 Answers 2

1

You only need a map to return each name.

var fruits = [
    {
        name: 'apple',
        color: 'golden'
    },
    {
        name: 'pear',
        color: 'green'
    },
    {
        name: 'mango',
        color: 'yellow'
    }
]

console.log(getFruitNames(fruits))

function getFruitNames(fruits){
  return fruits.map(m => m.name)
}

Also a TS playgorund

Sign up to request clarification or add additional context in comments.

Comments

1

Array.prototype.map() is what you need.

It will create a new array populated with the results of calling the provided function on every element in the calling array.

var fruits = [
    {
        name: 'apple',
        color: 'golden'
    },
    {
        name: 'pear',
        color: 'green'
    },
    {
        name: 'mango',
        color: 'yellow'
    }
];


console.log(fruits.map(x => x.name))

more about map can be found here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

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.