[英]Normalize JSON to a custom schema
我有一组具有以下格式的对象
var arr = [
{
"productId": "123456",
"productName": "Test Product 1",
"description": [
"This is delicious",
"Suitable for vegetarian"
],
"attributes": {
"internalId": "091283"
"category": "Dairy"
},
"order": 1
}
];
我正在尝试映射到如下所示的内容
[
[{
{
"name": "productId",
"value": "123456"
},
{
"name": "productName",
"value": "Test Product 1"
},
{
"name": "description",
"value": ["This is delicious", "Suitable for vegetarian"]
},
{
"name": "attributes",
"value": {
{
"name": "internalId",
"value": "091283"
},
{
"name": "category",
"value": "Dairy"
}
}
},
{
"name": "order",
"value": 1
}
}]
]
在继续之前,我尝试映射简单的属性,现在坚持只获取循环中每个对象的最后一个属性。
假设我不知道传入数据的格式是什么,以及如何将 JSON 对象规范化为我想要的格式?
normalizeJson = (array) => {
for(i = 0; i < array.length; i++){
normalizedJson[i] = {};
Object.keys(array[i]).forEach(key => {
if (array[i][key] && typeof array[i][key] === "object") {
// normalizeJson(obj[key]);
// console.log(key + ' is object');
return;
} else {
o = {};
o["name"] = key;
o["value"] = array[i][key];
normalizedJson[i] = o;
// normalizedJson[i]["name"] = key;
// normalizedJson[i].value = array[i][key];
// console.log(key);
return;
}
});
}
console.log(normalizedJson);
};
或者有没有我可以使用的库来实现这一目标?
尝试这个
var obj = [ { productId: "123456", productName: "Test Product 1", description: ["This is delicious", "Suitable for vegetarian"], attributes: { internalId: "091283", category: "Dairy", }, order: 1, }, ]; function normalizeObject(obj) { var result = []; if (Array.isArray(obj)) { for (let i of obj) { result.push(normalizeObject(i)); } } else if (typeof obj == "object") { for (let i of Object.keys(obj)) { result.push({ name: i, value: normalizeObject(obj[i]) }); } } else { return obj; } return result; } console.log(JSON.stringify(normalizeObject(obj), null, 2));
这种循环方法称为递归。 这是通过调用函数本身来循环的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.