-1

I have an array of objects, similar to the below:

const objectArray = [
  { 
    key1: 'value1a',
    key2: 'value2a',
    key3: 'value3a',
  },{ 
    key1: 'value1b',
    key2: 'value2b',
    key3: 'value3b',
  },{ 
    key1: 'value1c',
    key2: 'value2c',
    key3: 'value3c',
  },
];

and I would like to get an array containing all the values stored in, say, key2.

At the moment, my code looks as follows:

const valueArray = [];
objectArray.forEach((object) => {
  valueArray.push(object.key2);
});

This then results in

const valueArray = ['value2a', 'value2b', 'value2c'];

It feels like there is probably a more eloquent way to achieve the same thing, in just one line but I can't for the life of me figure out how to do that - can someone point me towards some documentation, or example code on how to do that please

lioness99a
  • 327
  • 4
  • 19

4 Answers4

1

Array.prototype.map()

const objectArray = [
    {
        key1: 'value1a',
        key2: 'value2a',
        key3: 'value3a',
    },
    {
        key1: 'value1b',
        key2: 'value2b',
        key3: 'value3b',
    },
    {
        key1: 'value1c',
        key2: 'value2c',
        key3: 'value3c',
    },
];

const result = objectArray.map(obj => obj.key2);

console.log(result);
Nikita Madeev
  • 4,284
  • 9
  • 20
1

You can map objectArray:

const valueArray = objectArray.map(o => o.key2);
Aplet123
  • 33,825
  • 1
  • 29
  • 55
1

You can use Array#map (which creates a new array with the result of applying a callback with each element) with destructuring.

const objectArray = [
  { 
    key1: 'value1a',
    key2: 'value2a',
    key3: 'value3a',
  },{ 
    key1: 'value1b',
    key2: 'value2b',
    key3: 'value3b',
  },{ 
    key1: 'value1c',
    key2: 'value2c',
    key3: 'value3c',
  },
];
const res = objectArray.map(({key2})=>key2);
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

Here is how you can do it for any key:

const objectArray = [
  {
    key1: 'value1a',
    key2: 'value2a',
    key3: 'value3a',
  }, {
    key1: 'value1b',
    key2: 'value2b',
    key3: 'value3b',
  }, {
    key1: 'value1c',
    key2: 'value2c',
    key3: 'value3c',
  },
];

function getByKey(key) {
  return objectArray.reduce((acc, red) => acc = [...acc, red[key]], [])
}

console.log(getByKey("key2"));
tdranv
  • 1,140
  • 11
  • 38