这里有一个例子:
原始json:
[
{
"id": 1,
"name": "item1",
"description": "test1"
},
{
"id": 2,
"name": "item2",
"description": "test2"
},
{
"id": 3,
"name": "item3",
"description": "test3"
}
]
转换后:
[
{
"id": 1,
"order": "item1",
"task": "test1"
},
{
"id": 2,
"order": "item2",
"task": "test2"
},
{
"id": 3,
"order": "item3",
"task": "test3"
}
]
到目前为止,我一直在这样做,但当添加新形式的数据时,它就不那么容易扩展了:
newjson = [];
oldjson.forEach(elem => {
newjson.push({
id: elem.id,
order: elem.name,
task: elem.description
});
});
我想要的是有一个函数,它可以使用类似于以下的值对列表将数据从一种形式转换为另一种形式:
propertyMapping = [
["id","id"],
["name","order"],
["description","task"]
];
您可以从传递的属性数组中创建一个Map
,并在将Object.entries
映射到Map
之后返回一个Object.fromEntries
。此处接受数组或单个对象,并相应地重新映射。
function remapProperties(objectOrArray, propertyMapping) {
const propertyMap = new Map(propertyMapping);
const remap = o => Object.fromEntries(
Object.entries(o).map(([k, v]) => [propertyMap.get(k) ?? k, v]));
return Array.isArray(objectOrArray)
? objectOrArray.map(remap)
: remap(objectOrArray);
}
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));
// also accepts individual objects
console.log(remapProperties({
"id": 1,
"name": "item1",
"description": "test1"
}, propertyMapping));
您可以在属性映射上循环,如果数据属性与一个属性映射匹配,则可以在类似array.map 的循环中更改porty
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);