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

Time:04-13

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:

[
  {
    "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"]
];

CodePudding user response:

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

CodePudding user response:

you can loop on property mapping and if data properties match to one property mapping change porty in a loop like array.map

const data = [{
    "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"]
];

let result = data.map(elem => {
  let final = {};
  propertyMapping.forEach(property => {
    if (elem[property[0]]) {
      final[property[1]] = elem[property[0]];
    }
  });
  return final;
});

console.log(result);

  • Related