有時候遇到一個牛逼一點的後端,我們前端能省不少事情啊,就像這次本來需要後臺返回二維對象或者數組的,可是人家說不方便,直接返回來obj = {app_one: 'appOne',product_three: 'productThree',}這種,要求我們自己處理。下面直接上demo代碼:
<script>
var obj = {
app_one: 'appOne',
app_two: 'appTwo',
files_six: 'filesSix',
app_three: 'appThree',
product_one: 'productOne',
product_two: 'productTwo',
product_four: 'productFour',
files_seven: 'filesSeven',
product_five: 'productFive',
maiboard_one: 'maiboardOne',
template_three: 'templateThree',
files_eight: 'filesEight',
template_four: 'templateFour',
files_one: 'filesOne',
files_two: 'filesTwo',
files_three: 'filesThree',
product_three: 'productThree',
files_four: 'filesFour',
files_five: 'filesFive'
},
obj01 = {}, obj02 = {}, name = '', str = 'jing'
for (const key in obj) {
name = key.split('_')[0];//以_分割key,然後取新數組的第一個即分類標準
obj02 = {};
obj02[key] = obj[key];//當前的key-value重新賦值給新對象
//當獲取的標準不存在時給obj01添加一個屬性(爲數組),name+','是爲了防止indexOf出現誤判
if (str.indexOf((name + ',')) > -1) {
obj01[name].push(obj02);//往數組添加對象
} else {
str += (name + ',')
obj01[name] = [];
obj01[name].push(obj02);//往數組添加對象
}
}
console.log(obj01)
</script>
輸出結果: