Home > database >  Making array in particular format using javascript object
Making array in particular format using javascript object

Time:01-21

I have an object as follows:

{
        "id":1,
        "vol":"0.0"
        "vol_per":"0.0%"
        "ABC":"8.30",
        "OFG":"13.85",
        "SPG":"70.80"
        
  }

from this object I want to create a array in following format.

data = [
{field:'vol',header:'VOL'},
{field:'vol_per',header:'VOL%'},
{field:'ABC',header:'ABC'},
{field:'OFG',header:'OFG'},
{field:'APG',header:'SPG'}
]

in this array, field will have value same as key of above object and header values will be similar to shown in data array. Similaryly at run time many attributes can come. How can I do that?

CodePudding user response:

const obj = {
  "id":1,
  "vol":"0.0",
  "vol_per":"0.0%",
  "ABC":"8.30",
  "OFG":"13.85",
  "SPG":"70.80"
}

const result = Object.entries(obj).filter(([k])=>k!=='id')
  .map(([k,v])=>(
    {field:k, header: `${k.toUpperCase().replace(/_PER$/, '%')}`
  }))

console.log(result)

CodePudding user response:

This would also work:

const input = {
  id: 1,
  vol: "0.0",
  vol_per: "0.0%",
  ABC: "8.30",
  OFG: "13.85",
  SPG: "70.80",
};

const processText = (text) => {
  return text.toString().replace(/_per/g, "%").toLocaleUpperCase();
};

const output = Object.entries(input).reduce((prev, [field]) => {
  if (field !== "id") {
    prev = prev.concat([{ field, header: processText(field) }]);
  }
  return prev;
}, []);

console.log(output);

Using Array.prototype.reduce() and Object.entries()

  • Related