How to convert object into array?

I am having some issues understanding how to create an array from an object, This object is one piece of an array(results from a mysql query) maybe I just need more coffee:

Current object looks like this:

{"task_id":4,
"assigned":"testuser",
"due_date":"2020-08-16",
"complete_by":"14:33",
"details":"some details"}

My goal is to have an array that looks like this:

{
"title": "task_id",
"value": "4"
},
{
"title": "assigned",
"value": "testuser"
},
{
"title": "due_date",
"value": "2020-08-16"
},
{
"title": "complete_by",
"value": "14:33"
},
{
"title": "details",
"value": "some details"
}

New to node red and I am not a dev, be gentle... lol

Thanks!

Some more context would be useful for suggesting the best solution, so is the object in msg.payload or are you already in a Function node, interpreting the sql node result array, or something else?
However, can you describe what you are going to do with the array, there may be a better way of solving the larger problem.

This it the data returned from an upstream mysql query(direct output from the mysql node). are you thinking there might be a better way to format the output of the mysql query?

Here is a snip of a payload:

image

Thanks!

This will work as described in your first post...

add a function node and feed your database output to it...

var el0 = msg.payload[0]; //get element zero of your data
var arr = []; //a new array for populating results

for(let prop in el0) {
  let val = el0[prop];
  arr.push({
    "title": prop,
    "value": val
  });
}

msg.payload = arr; //set payload
return msg; //return the msg

caveats

This only works with one element of your array (because the 2nd element would create duplicates) but if you want that then put the whole thing in a loop.

This is a test to prove it works...

That is exactly what I was looking to do! Just need to figure out the proper way to do the loop now!

Thank you very much!!

Try this...

var outer = msg.payload; //get your data
var arr = []; //a new array for populating results

for(let i = 0; i < outer.length; i++) {

let el = outer[i];
for(let prop in el) {
  let val = el[prop];
  arr.push({
    "title": prop,
    "value": val
  });
}

}
msg.payload = arr; //set payload
return msg; //return the msg

Notes:

  • written on my phone (untested)
  • No error checking
1 Like