Search code examples
javascriptarraysangulartypescriptjavascript-objects

JavaScript Convert Array Of Objects to Arrays For only Specific Key


I have an array of objects

{
    "tags": [{
            "id": "1",
            "data": [{
                    "bs": 1617779042313,
                    "bstp": 1617779099999,
                    "maxA": 1617779050311,
                    "maxV": 10,
                    "minA": 1617779050310,
                    "minV": 10,
                    "q": 3
                },
                {
                    "bs": 1617779100000,
                    "bstp": 1617779519999,
                    "maxA": 1617779100236,
                    "maxV": 10,
                    "minA": 1617779100231,
                    "minV": 10,
                    "q": 2
                }
            ]
        },
        {
            "id": "2",
            "data": [{
                    "bs": 1617779042313,
                    "bstp": 1617779099999,
                    "maxA": 1617779050311,
                    "maxV": 10,
                    "minA": 1617779050310,
                    "minV": 10,
                    "q": 3
                },
                {
                    "bs": 1617779100000,
                    "bstp": 1617779519999,
                    "maxA": 1617779100236,
                    "maxV": 10,
                    "minA": 1617779100231,
                    "minV": 10,
                    "q": 2
                }
            ]
        }

    ]
}

Output

{
    "tags": [{
            "id": "1",
            "data": [
                [1617779050311, 10, 3],
                [1617779100236, 10, 2]
            ]
        },
        {
            "id": "2",
            "data": [
                [1617779050311, 10, 3],
                [1617779100236, 10, 2]
            ]
        }

    ]
}

I want to format this array of objects into array of arrays

for the "data" key i need to get the value of specific keys and insert in array

specific keys - [MaxA, maxV, q]

How can I do it? Any small help appreciated..:)

efewfewfewfewfewfwefwefewfewfwefewfkfopkr3po2i50493543iropjgoprevm


Solution

  • You can use map. See the code snippet below:

    const data = [
      {
        bs: 1617779042313,
        bstp: 1617779099999,
        maxA: 1617779050311,
        maxV: 10,
        minA: 1617779050310,
        minV: 10,
        q: 3,
      },
      {
        bs: 1617779100000,
        bstp: 1617779519999,
        maxA: 1617779100236,
        maxV: 10,
        minA: 1617779100231,
        minV: 10,
        q: 2,
      },
    ];
    
    const keys = ["maxA", "maxV", "q"];
    
    console.log(data.map((d) => keys.map((k) => d[k])));