Referring to Json object problem

Hi,
I have problem with javascript referring to particular keys. I need to rearrange incoming Json to other Json layout however debug throws me an error: "TypeError: Cannot read property 'RP' of undefined". My guess that it is because key names are stored as strings in the array dataNames. I think that they should be called in some other way but I can not figure out how. Here is the function code & incoming Json:

[
    {
    "0":{"RP":55.9,"AP":87.3,"PF":0.6,"V":230.8,"I":0.4},
    "1":{"RP":391.3,"AP":467.9,"PF":0.8,"V":227.6,"I":2.1},
    "2":{"RP":47.7,"AP":80.9,"PF":0.6,"V":231.4,"I":0.3},
    "3":{"T":22.1,"H":23.1,"P":987.2,"A":219}
    }
]

function myFunction(data)
{
    let arrange = [];
    const colNames = ['Real Power','Apparent Power','Power Factor','Voltage','Amps'];
    const dataNames = ['RP','AP','PF','V','I'];

    for (i=0; i<5; i++)
    {
        let newData = {
            "" : colNames[i],
            "Phase 1": data['0'][dataNames[i]],
            "Phase 2": data['1'][dataNames[i]],
            "Phase 3": data['2'][dataNames[i]]
        }

        arrange.push(newData);
    }

    return arrange;
}


var msgout = myFunction(msg.payload);
msg.payload = msgout;
return msg;

Your object is in an array of 1 element, try sending data as myFunction(msg.payload[0]);

1 Like

What an epic fail! :slight_smile: Yes, of course you are right and it works. Well I spent an hours to dig into enums and some other stuff while solution was much more silly. Thanks a lot! :slight_smile:

Don't forget that if you use the debug node, you can grab the correct path from the debug display.

Thanks a lot. Yes, I actually use this copy path option in debug but occasionally not this time. That is why I got in trouble. :slight_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.