1

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?

Roma
  • 23
  • 3
  • 2
    What's the logic for calculating the `header` value? – Nicholas Tower Jan 21 '23 at 05:29
  • What do you mean by _“similar to shown in data array”_? Where do `"VOL"` and `"VOL%"` come from? Do you mean something like this: [Convert object to array of key–value objects like `{ name: "Apple", value: "0.6" }`](/q/47863275/4642212)? – Sebastian Simon Jan 21 '23 at 05:29
  • nothing it is our wish to give header value – Roma Jan 21 '23 at 05:36
  • @Roma The values for each `header` property have to come from _somewhere_. You need to be more specific if you want answers instead of guesses. [Edit] your post and clarify it. – Sebastian Simon Jan 21 '23 at 05:43

2 Answers2

0

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)
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27
0

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()

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43