[英]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.