0

I have a json object for chart like below:

{
  "results": [
    {
      "dataSets": {
        "One": {
          "label": "testLabel",
          "labels": "test",
          "data": [
            "10",
            "58"
          ]
        }
      },

      "chart": [
        {
          "key": "test",
          "label": "chart-1",
          "chartType": "bar",
          "order": "1",
          "dataSets": [
            {
              "style": "line",
              "key": "One"
            },
          ]
        }
      ]
    }
  ]
}

I want to get dataSets values like label, labels, data of “one” in chart’s dataSets by providing “one” as key.

Is it possible to do in javascript or vue?

Hao Wu
  • 17,573
  • 6
  • 28
  • 60
Nikhat
  • 3
  • 2
  • https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json/ This question would help. – faizan Sep 07 '20 at 12:59

1 Answers1

0

Yes, it is possible. But you will need to make a series of Array.map() to achieve this.

const results = [{
  dataSets: {
    One: {
      label: "testLabel",
      labels: "test",
      data: ["10", "58"]
    }
  },

  chart: [{
    key: "test",
    label: "chart-1",
    chartType: "bar",
    order: "1",
    dataSets: [{
      style: "line",
      key: "One"
    }]
  }]
}];

const modifiedResult = results.map(result => {
  const outerDataSets = result.dataSets;
  result.chart = result.chart.map(chart =>
    chart.dataSets.map(innerDataSet => ({
      ...innerDataSet,
      ...outerDataSets[innerDataSet.key]
    }))
  );
  return result;
});

console.log(modifiedResult);

Also if you are working with Vue, I think its best to put the modification of result on the computed so it will always try to add those dataSets additional data to the chart's dataSets.

Here a sample demo for implementation in Vue.

Blackraspberryyy
  • 2,016
  • 2
  • 11
  • 22