[英]how to encode/ change the format of existing json to another using angular/javascript
這里我有以下格式的json
目前格式
{
"info": {
"laptop": {
},
"config": {
"properties": {
"ram": {
},
"processor": {
},
"hdd": {
}
}
},
"link": {
},
"name": {
},
"company": {
"properties": {
"model": {
},
"maker": {
"type": "integer"
},
"country": {
"type": "text"
},
"enterprise": {
}
}
}
}
}
我正在使用某些插件,例如ngx-tree,primeng插件,其數據需要采用以下不同格式
必填格式
[
{
name: 'laptop',
},
{
name: 'config',
children: [
{ name: 'ram', children: [] },
{ name: 'processor' },
{name:'hdd'}
]
},
{
name: 'link',
children: []
},
{
name: 'name',
children: []
},
{
name: 'company',
children: [
{ name: 'model' },
{ name: 'maker' },
{ name: 'country' },
{ name: 'enterprise' }
]
}
];
現在我的問題是如何將數據從當前格式更改為所需格式? 有什么建議可以讓我改變嗎
您可以遞歸地遍歷輸入對象,將其映射為所需的格式,如下所示:
function recursiveConvert(input) {
let converted = []
for(i in input){
converted.push({
name: i,
children: []
})
if(input[i].properties) {
converted[converted.length - 1].children.push(recursiveConvert(input[i].properties))
}
}
return converted
}
如果您不希望有空的子數組,只需將其更改為:
function recursiveConvert(input) {
let converted = []
for(i in input){
converted.push({
name: i
})
if(input[i].properties) {
let lastInsert = converted[converted.length - 1]
lastInsert.children = [recursiveConvert(input[i].properties)]
}
}
return converted
}
請確保使用recursiveConvert(myInput.info)
調用它,因為它不需要該包裝對象。
你可以做:
const json = {"info": {"laptop": {},"config": {"properties": {"ram": {},"processor": {},"hdd": {}}},"link": {},"name": {},"company": {"properties": {"model": {},"maker": {"type": "integer"},"country": {"type": "text"},"enterprise": {}}}}}; const result = Object.keys(json.info).map(k => ({ name: k, children: json.info[k].properties ? Object.keys(json.info[k].properties).map(kk => ({name: kk})) : [] })); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
這是一個單行的純功能解決方案:
const input = { "info": { "laptop": { }, "config": { "properties": { "ram": { }, "processor": { }, "hdd": { } } }, "link": { }, "name": { }, "company": { "properties": { "model": { "properties": { "apple": {}, "banana": {}, "pear": {} } }, "maker": { "type": "integer" }, "country": { "type": "text" }, "enterprise": { } } } } } const convert = input => Object .entries(input) .map(([name, value]) => ({ name, children: convert(value.properties || {}) })) console.log(convert(input.info));
這是es2015版本:
function convert(input) {
return Object.keys(input).map(function(name) {
return {
name: name,
children: convert(input[name].properties || {})
};
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.