Search code examples
javascriptnode-red

How to extract multiple value from a json in node red


I am trying to extract multiple values from multiple JSON arrays to create a pie chart.

The below function only able to get a single value but what I want is to get all values from those arrays for example, tag should return "untagged","HK_Online","HK_Order/Change address" but it only return "HK_Online" at the moment.

My function node

var value = msg.payload.lines[0][1].value;
var tag = msg.payload.lines[1][0].value;

msg.topic = tag;
msg.payload = value;
return msg;

JSON data

{
  "axes": {
    "x": [
      { "name": "Tag","type": "string" },
      { "name": "Total","type": "number" },
      { "name": "Percentage","type": "percent" },
      { "name": "Delta", "type": "delta" }
    ]
  },
  "lines": [
    [
      { "type": "string","value": "Untagged" },
      { "type": "number","value": 1 },
      { "type": "percent","value": 20 },
      { "type": "delta", "value": 100 }
    ],
    [
      { "type": "string","value": "HK_Online" },
      { "type": "number","value": 4 },
      { "type": "percent","value": 80 },
      { "type": "delta","value": 100 }
    ],
    [
      { "type": "string","value": "HK_Order/Change address" },
      { "type": "number","value": 1 },
      { "type": "percent","value": 20 },
      { "type": "delta","value": 100 }
    ]
  ]
}

Solution

  • You can use map method to create new array from the lines array

    let lines = msg.payload.lines
    
    let tag = lines.map(item => item[0].value)
    let value = lines.map(item => item[1].value)