我们如何只转换'项目' (对象类型)键到数组类型:
var arr = [{
"title": "Custom title",
"id": "id1",
"icon": "fa fa-reorder",
"other": {
"3991": {
"title": "Some title",
"link": "#",
"icon": "",
"items": {
"3992": {
"title": "Some title",
"link": "#",
"icon": ""
}
}
},
"3993": {
"title": "Some title",
"link": "#",
"icon": ""
}
}
}];
要:
var arr = [{
"title": "Custom title",
"id": "id1",
"icon": "fa fa-reorder",
"other": {
"3991": {
"title": "Some title",
"link": "#",
"icon": "",
"items": [{
"title": "Some title",
"link": "#",
"icon": ""
}]
},
"3993": {
"title": "Some title",
"link": "#",
"icon": ""
}
}
}];
我需要分别选择每次更改指定键的类型。我搜索了一些阵列步行者,但没有成功。
示例:
var newArr = change_key_type({
'arr' : arr,
'key' : 'items',
'type' : 'array'
});
答案 0 :(得分:0)
您可以迭代并为所有items
构建一个新数组。
function walk(a) {
typeof a === 'object' && Object.keys(a).forEach(function (k) {
if (k === 'items' && typeof a.items === 'object') {
a.items = Object.keys(a.items).map(function (k) {
walk(a.items[k]);
return a.items[k];
});
return;
}
walk(a[k]);
});
}
var arr = [{ "title": "Custom title", "id": "id1", "icon": "fa fa-reorder", "other": { "3991": { "title": "Some title", "link": "#", "icon": "", "items": { "3992": { "title": "Some title", "link": "#", "icon": "" } } }, "3993": { "title": "Some title", "link": "#", "icon": "" } } }];
arr.forEach(walk);
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');