0

I have an object, which has 2 objects whithin and some properties of interest.

myObject = {
  "chart":{
     "data":[
        {
           "name":"First",
           "x":[
              "2000-01-01T00:00:00",
              "2000-02-01T00:00:00",
              "2000-03-01T00:00:00",
           ],
           "y":[
              1,
              2,
              3,
           ],
           "type":"scatter"
        },
        {
          "name":"Second",
          "x":[
             "2000-01-01T00:00:00",
             "2000-02-01T00:00:00",
             "2000-03-01T00:00:00",
          ],
          "y":[
             1,
             2,
             3,
          ],
          "type":"scatter"
       },  
     ],
     "otherKey":{
        "whatever":"line"
     }
  },
};

I'm trying to create a new "object" which is an array of objects, and the only keys of interest are name and point, with point being an array of x and y combined.

newObject = [
  {
      "name":"First",
      "point":[
        ["2000-01-01T00:00:00", 1],
        ["2000-02-01T00:00:00", 2],
        ["2000-03-01T00:00:00", 3],
      ],
  },
  {
    "name":"Second",
    "point":[
      ["2000-01-01T00:00:00", 1],
      ["2000-02-01T00:00:00", 2],
      ["2000-03-01T00:00:00", 3],
    ],
  },
];

I'm trying to use map and filter function but I'm getting lost somewhere in the middle.

newObject = myObject.chart.data.map((value) =>  {
  return [
    value.x,
    value.y
  ]
});

I think I need to concatenate them properly. I'm a JS begginer, any tip or guidance would help, thanks.

Bernardo Marques
  • 925
  • 2
  • 10
  • 33
  • 1
    This looks like something `reduce` is better for. https://stackoverflow.com/questions/5732043/javascript-reduce-on-array-of-objects – Joseph Cho May 22 '20 at 14:20

2 Answers2

1

you are missing how to combine those arrays of x and y, this implementation should help you

newObject = myObject.chart.data.map((value) =>  {
  return {
        name: value.name,
        point: combine(value.x, value.y)
  }
});


function combine(arr1, arr2) {
    let ans = [];
    for(let i = 0; i < arr1.length; i++) { 
        ans.push([arr1[i], arr2[i]])
    }

    return ans;
}
ashish singh
  • 6,526
  • 2
  • 15
  • 35
0

You can make use of map.

myObject = { "chart":{ "data":[ { "name":"First", "x":[ "2000-01-01T00:00:00", "2000-02-01T00:00:00", "2000-03-01T00:00:00", ], "y":[ 1, 2, 3, ], "type":"scatter" }, { "name":"Second", "x":[ "2000-01-01T00:00:00", "2000-02-01T00:00:00", "2000-03-01T00:00:00", ], "y":[ 1, 2, 3, ], "type":"scatter" }, ], "otherKey":{ "whatever":"line" } },};

result = myObject.chart.data.map(({name, ...rest})=>{
    point = rest.x.map((k,i)=>[k,rest.y[i]]);
    return {name, point};
});

console.log(result);
gorak
  • 5,233
  • 1
  • 7
  • 19