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