2017-11-16 8 views
0

데이터 배열이 있으며 일부 속성이 배열입니다. 그 배열을 평평하게 만들지 않으므로 아래에 설명 된대로 속성 중 아무 것도 배열이 아닙니다.JavaScript를 사용하는 자식 개체는 Array (SQL에 nosql 데이터 형식)와 같은 SQL로 변환해야합니다.

입력 내가 그것을 물어 때

[ 
    {"name":"James","education_year":2014,"education_degree":"MS"}, 
    {"name":"James","education_year":2012,"education_degree":"BS"}, 
    {"name":"Bond","education_year":2011,"education_degree":"MS"}, 
    {"name":"Bond","education_year":2009,"education_degree":"BS"} 
] 

https://sqlify.io/convert CSV 형식으로 변환 할 않습니다

[{ 
    "name": "James", 
    "education": [ 
     { "year": 2014, "degree": "MS" }, 
     { "year": 2012, "degree": "BS" }] 
}, { 
    "name": "Bond", 
    "education": [ 
     { "year": 2011, "degree": "MS" }, 
     { "year": 2009, "degree": "BS" }] 
}] 

출력. 그러나 나는 그 서비스를 사용할 수 없다.

어떤 방식 내가 원하는 생산할 수있는 출력과 Array#map

답변

1

반복 처리하고 요청 된 포맷에 새로운 오브젝트 education이 맵이다. spreadArray#concat을 사용하여 결과를 병합합니다.

Object # assign을 사용하여 개체를 만듭니다. 할당 내부 배열 번호는 필요한 형식으로 각 속성을 매핑 및 확산 :

const data = [{ 
 
    "name": "James", 
 
    "education": [ 
 
     { "year": 2014, "degree": "MS" }, 
 
     { "year": 2012, "degree": "BS" }] 
 
}, { 
 
    "name": "Bond", 
 
    "education": [ 
 
     { "year": 2011, "degree": "MS" }, 
 
     { "year": 2009, "degree": "BS" }] 
 
}]; 
 

 
const result = [].concat(...data.map(({ name, education }) => 
 
    education.map(({ year, degree }) => ({ name, education_year: year, education_degree: degree }) 
 
))); 
 

 
console.log(result);

객체에 여러 하위 배열을 처리 할 수있는 일반 버전 :

const data = [{"name":"James","lname":"Parker","education":[{"year":2014,"degree":"MS"},{"year":2012,"degree":"BS"}],"job":[{"year":2017,"title":"senior developer"},{"year":2017,"title":"developer"},{"year":2014,"title":"junior"}]},{"name":"Bond","lname":"Peter","education":[{"year":2011,"degree":"MS"},{"year":2009,"degree":"BS"}],"job":[{"year":2014,"title":"ninja"},{"year":2012,"title":"rogue"}]}]; 
 

 
const createKey = (prefix, key) => `${prefix}_${key}`; 
 

 
const result = [].concat(...data.map((el) => 
 
\t Object.entries(el) 
 
    .map(([k, v]) => Array.isArray(v) ? 
 
     v.map((o) => Object.entries(o).reduce((r, [key, val]) => Object.assign(r, { [createKey(k, key)]: val }), {})) 
 
     : 
 
     { [k]: v } 
 
    ) 
 
    \t .reduce((r, s) => 
 
    \t Array.isArray(s) ? 
 
     \t [].concat(...r.map((o) => s.map((q) => Object.assign({}, o, q)))) 
 
     : 
 
     r.map((o) => Object.assign({}, o, s)) 
 
     , [{}]) 
 
)); 
 

 
console.log(result);

+0

이 답변을 수락 해 주셔서 감사합니다.하지만 제 문제는 엄청난 수의 속성을 가지고 있습니다. o 하드 코드 된 모든 것은 작동하지 않습니다. 같은 속성 "이름", 교육 학위 등이 여기에서 걸릴 수있는 몇 가지 일반적인 기능을 만들 수있는 좋은 출발점입니다. 일단 끝나면 게시 할 것입니다. – gaurang171

+0

다음은 일반적인 코드입니다. https://jsfiddle.net/qnetgvfy/1/ – gaurang171

+0

개체의 여러 하위 배열을 처리 할 수있는 일반 버전으로 업데이트되었습니다. –