2017-12-15 14 views
3

내가 배열 어떻게 JSON 배열로 배열을 변환 할 수는 <pre><code>[{code:'N',description:'Normal'}, {code:'S',description:'Severe'}, {code:'C',description:'Confidential'} ] </code></pre> <p></p>이 달성 할 수있는 방법이 있나요,

var a = ['N','Normal','S','Severe','C','Confidential'] 

내가 다음과 같은 출력 형식을 필요하다고 한 객체?

+0

나 배열 패턴은 알려 주시기 바랍니다 영원히 like var a = [ 'N', '보통', 'S', '심각', 'C', '기밀'] –

답변

2

을 시도해보십시오

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);

0

다음과 같이 Array.prototype.reduce()를 사용할 수있는이 솔루션

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);

+0

감사합니다 saurabh :) – tracer