我有一个数组说
var a = ['N','Normal','S','Severe','C','Confidential']
我需要输出格式如下,
[{code:'N',description:'Normal'},
{code:'S',description:'Severe'},
{code:'C',description:'Confidential'}
]
有没有办法实现这个目标?
答案 0 :(得分:2)
您可以按如下方式使用Array.prototype.reduce()
:
const array = ['N', 'Normal', 'S', 'Severe', 'C', 'Confidential'];
const object = array.reduce((result, value, i) => {
i % 2 || result.push({code: value, description: array[i + 1]});
return result;
}, []);
console.log(object);
答案 1 :(得分:0)
试试这个解决方案
var a = ['N','Normal','S','Severe','C','Confidential']
var output = [];
for (var i = 0; i < a.length; i++) {
var tmpObj = {};
if (i%2 == 0) {
tmpObj.code = a[i];
if (a[i+1]) {
tmpObj.description = a[i+1];
}
output.push(tmpObj);
}
}
console.log(output);