Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the most scalable way to convert json data from one form to another in javascript?

Here’s an example:

Original json:

[
  {
    "id": 1,
    "name": "item1",
    "description": "test1"
  },
  {
    "id": 2,
    "name": "item2",
    "description": "test2"
  },
  {
    "id": 3,
    "name": "item3",
    "description": "test3"
  }
]

After conversion:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  {
    "id": 1,
    "order": "item1",
    "task": "test1"
  },
  {
    "id": 2,
    "order": "item2",
    "task": "test2"
  },
  {
    "id": 3,
    "order": "item3",
    "task": "test3"
  }
]

So far I’ve been doing it like so, but it’s not that easily scalable when new forms of data gets added:

newjson = [];

oldjson.forEach(elem => {
  newjson.push({
    id: elem.id,
    order: elem.name,
    task: elem.description
  });
});

What I’m looking for is having one function that would be able to convert data from one form to another both ways using some value pair list similar to this:

propertyMapping = [
  ["id","id"],
  ["name","order"],
  ["description","task"]
];

>Solution :

You could create a Map from the passed array of properties and return an Object.fromEntries after mapping the Object.entries against the Map. Here using concat to allow for individual objects to be passed as well.

function remapProperties(objArray, mapping) {
  const propertyMap = new Map(mapping);
  return [].concat(objArray).map(o =>
    Object.fromEntries(
      Object.entries(o).map(([k, v]) => [propertyMap.get(k) ?? k, v]))
  )
}

const input = [{ "id": 1, "name": "item1", "description": "test1" }, { "id": 2, "name": "item2", "description": "test2" }, { "id": 3, "name": "item3", "description": "test3" }];
const propertyMapping = [["id", "id"], ["name", "order"], ["description", "task"]];

console.log(remapProperties(input, propertyMapping));

// the 'concat' allows individual objects to be passed too
console.log(remapProperties({
  "id": 1,
  "name": "item1",
  "description": "test1"
}, propertyMapping));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading