0

I have an array with some key value data.

var data = [
    {
        speed : 130,
        acceleration: 3.8
    },
    {
        speed : 120,
        acceleration: 3
    },
    {
        speed : 90,
        acceleration: 1.2
    },
    {
        speed : 140,
        acceleration: 1.4
    },
]

I would like to get all the 'speed' items into different array. I could use data.map(x => x.speed) but here I do not know the key name.

I want to something like

var extract = getSubArray(data, 'speed');
Chandra Eskay
  • 2,163
  • 9
  • 38
  • 58
  • 3
    Inside `getSubArray`, you can use your `map` with bracketed property access; see the linked question's answers. E.g., `function getSubArray(data, propName) { return data.map(x => x[propName]); }` or with ES2015+ destructuring: `function getSubArray(data, propName) { return data.map(([propName]: value) => value); }` though...yeah, I guess destructuring isn't really helpful there. :-) – T.J. Crowder Feb 24 '20 at 11:42

1 Answers1

1

You can just add that logic in a function:

var data = [{
    speed: 130,
    acceleration: 3.8
  },
  {
    speed: 120,
    acceleration: 3
  },
  {
    speed: 90,
    acceleration: 1.2
  },
  {
    speed: 140,
    acceleration: 1.4
  },
]

function getSubArray(dataArr, prop) {
 return dataArr.map(x => x[prop]);
}
var extract = getSubArray(data, 'speed');

console.log(extract);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
  • 1
    Solved using the same steps: var extract = getSubArray(data, 'speed'); getSubArray(data, indexKey) { return data.map(x => x[indexKey]); } – Chandra Eskay Feb 24 '20 at 11:55