Home > database >  matching the arrays react js
matching the arrays react js

Time:10-12

This may be a silly question.

I'm creating a dashboard and as a first step, i used dummy hard-coded values to build the dashboard. after that, I got data from API and now I want to use data from API instead of using hard-coded data.

enter image description here

Expanded the API array:

enter image description here API array represents data from API and hardcoded array represents data from hard coded data. as you can see, the array format differs from API to hardcoded. instead of array inside array can we have the data format the same as in a hardcoded array(just values only)?

const hardcoded = [
    [118, 1, 2, 3, 100, 2, 10, 108],
    [3, 1, 1, 1, 3, 4, 5],
    [10, 4, 2, 12, 45, 356],
    [8, 1, 2, 3, 1],
    [3, 1, 1, 100],
    [10, 491, 2],
];

const dataFromApi1 = lostRecoveryInfo?.map(
    ({ lost, recoveryTimespan, netLost, netRecovered }) => [
        lost,
        recoveryTimespan?.map(({ count }) => count),

        netLost,
        netRecovered,
    ],
);

console.log("------------------->API", dataFromApi1);
console.log("------------------->hardcoded", hardcoded);

Current data format from API and expected data format from API are given below:

enter image description here

CodePudding user response:

As simple as this:

yourApiData.map(x=>x.flat()) 

You can take a look at the docs on the funtions map and flat.

yourApiData = [
    [118, [1, 2, 3, 100, 2], 10, 108],
    [3, [1, 1, 1, 3], 4, 5],
    [10, [4, 2, 12], 45, 356],
    [8, [1, 2], 3, 1],
    [3, [1], 1, 100],
    [10, [], 491, 2],
]
console.log(yourApiData.map(x=>x.flat()))

CodePudding user response:

A suggestion is to try to replace the underscores/spaces/quotes using replace(). e.g.

const newData = key.replace("argument to be replaced", "value to replace argument");
console.log(newData);

I hope this was helpful.

  • Related