Get specific values from object when mapping through nested object

Viewed 714

I want to return an array with specific values of _time & _value. The function that I made is as followed:

getMachineData(data) {
    console.log(data)
    const result = data.map((innerArray) => {
        console.log(typeof innerArray)
        console.log(innerArray)
        // Map over the inner array
        return innerArray.map((item) => {
            console.log(item)
            return ({
                time: item._time,
                value: item._value
            });
        });
    });
    console.log(result);
};

But in this code the last console.log is never hit.

The innerArray data is as followed:

{ "result": "_result", "table": 0, "_start": "2021-01-06T14:35:53Z", "_stop": "2022-01-06T14:35:53Z", "_time": "2021-10-11T10:58:30Z", "_value": 0, "_field": "approved", "_measurement": "oee-data", "end_time_str": "2021-10-11T10:59:00Z", "machine": "almo", "start_time_str": "2021-10-11T10:58:30Z" }

The output:

enter image description here

2 Answers

Your innerArray is not not an Array but an Object. You can not map over an Object like innerArray.map... which will probably throw an error.

innerArray is an Object, so dont have to iterate. Just access the value directly. Replace below code

return innerArray.map((item) => {
            console.log(item)
            return ({
                time: item._time,
                value: item._value
            });
        });

with

return {
         time: innerArray._time,
         value: innerArray._value
       };

The optimized code will look like

getMachineData(data) {
    const result = data.map(({_time, _value}) => ({time: _time, value:_value }));
    console.log(result);
};
Related