Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get specific values from object when mapping through nested object

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{ "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

>Solution :

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);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading