skip to Main Content

First of all I am sorry If I couldn’t explained my problem because it is really hard for me to explain it but If you need more information I will try answer all. So I am trying to format this array of objects

[
    {
        "time": "18th",
        "open": 100,
        "closed": 60,
        "waiting": 12
    },
    {
        "time": "20th",
        "open": 120,
        "closed": 80,
        "waiting": 75
    },
    {
        "time": "22nd",
        "open": 170,
        "closed": 0,
        "waiting": 34
    },
]

To this in javascript. I don’t know what to do, I am not even sure if I can really format it, I need to create a dynamic chart and I realised that I can’t do it with the first format due to library restrictions.

{
    "time": ["18th", "20th", "22nd"],
    "graphData": [
        {
            "label": "open",
            "data": [100, 120, 170],
        },
        {
            "label": "closed",
            "data": [60, 80, 0],
        },
        {
            "label": "waiting",
            "data": [12, 75, 34],
        }
    ]
}

2

Answers


  1. const source = [
        {
            "time": "18th",
            "open": 100,
            "closed": 60,
            "waiting": 12
        },
        {
            "time": "20th",
            "open": 120,
            "closed": 80,
            "waiting": 75
        },
        {
            "time": "22nd",
            "open": 170,
            "closed": 0,
            "waiting": 34
        },
    ];
    
    const mapped = {
      time: source.map(item => item.time),
      graphData: ['open', 'closed', 'waiting']
        .map(label => ({label, data: source.map(item => item[label])}))
    };
    
    console.log(mapped);
    Login or Signup to reply.
  2. This is an alternative by using the function Array.prototype.forEach which loops once.

    const result = {time: [], graphData: {}},
          source = [{"time": "18th","open": 100,"closed": 60,"waiting": 12},{"time": "20th","open": 120,"closed": 80,"waiting": 75},{"time": "22nd","open": 170,"closed": 0,"waiting": 34},];
          
    source.forEach(({time, open, closed, waiting}) => {
      result.time.push(time);
    
      (result.graphData["open"] || (result.graphData["open"] = {label: "open", data: []})).data.push(open);
      (result.graphData["closed"] || (result.graphData["closed"] = {label: "closed", data: []})).data.push(closed);
      (result.graphData["waiting"] || (result.graphData["waiting"] = {label: "waiting", data: []})).data.push(waiting);
    });
    
    result.graphData = Object.values(result.graphData);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search