Search code examples
jsonvue.jsjavascript-objectssiblings

How to refer sibling element in JSON Javascript?


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?


Solution

  • 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.