Search code examples
javascriptreactjslodashramda.js

How do I get values from a nested array pushed into a flat array?


I have an api returning a dataset like this:

const data = {
  session: ....,
  timestamp: ....,
  samples: [
    {
      key: 'I',
      values: [
        { timing: '12356timingdatething', reading: -37.1234 },
        { timing: '12356timingdatething', reading: -32.1234 },
        { timing: '12356timingdatething', reading: 1.1234 },
        // ....
      ],
    },
    {
      key: 'I',
      values: [
        { timing: '12356timingdatething', reading: -100.1234 },
        { timing: '12356timingdatething', reading: 5.1234 },
        { timing: '12356timingdatething', reading: 5.3334 },
        // ....
      ],
    },
    {
      key: 'I',
      values: [
        { timing: '12356timingdatething', reading: -37.1234 },
        { timing: '12356timingdatething', reading: -32.1234 },
        { timing: '12356timingdatething', reading: 1.1234 },
        // ....
      ],
    },
  ]
}

what I want to do is grab values from samples and push them into a new array that will just be a flat array, something like this:

const newData = [
  [
    { timing: '12356timingdatething', reading: -37.1234 },
    { timing: '12356timingdatething', reading: -32.1234 },
    { timing: '12356timingdatething', reading: 1.1234 },
    // ....
    { timing: '12356timingdatething', reading: -100.1234 },
    { timing: '12356timingdatething', reading: 5.1234 },
    { timing: '12356timingdatething', reading: 5.3334 },
    // ....
    { timing: '12356timingdatething', reading: -37.1234 },
    { timing: '12356timingdatething', reading: -32.1234 },
    { timing: '12356timingdatething', reading: 1.1234 },
    // ....
  ]

I was able to get samples into a new array like so:

this.setState(prevState => ({
  newArray: [...prevState.newArray, [...data.samples] ]
}));

I'm open to using libraries like lodash or ramda if there's a library that exists that would make this easier.


Solution

  • You could use reduce() or flatMap():

    const newData = data.reduce((accumulated, current) => [...accumulated, ...current.values], []);
    

    Or:

    const newData = data.flatMap(item => item.values);