Home > OS >  Convert array of object to array of values of specific key
Convert array of object to array of values of specific key

Time:09-27

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

CodePudding user response:

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

CodePudding user response:

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

  • Related