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?

4
  • 2
    What's the logic for calculating the header value? Commented Jan 21, 2023 at 5: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" }? Commented Jan 21, 2023 at 5:29
  • nothing it is our wish to give header value Commented Jan 21, 2023 at 5: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. Commented Jan 21, 2023 at 5:43

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.