๐ ๋ฌธ์
let videoList = [
[
['id',1],
['title','first video'],
['description','This is first video'],
['view',24],
],
[
['id',2],
['title','second video'],
['description','This is second video'],
['view',17],
],
[
['id',3],
['title','third video'],
['description','This is third video'],
['view',15],
],
];
๋น๋์ค์ ๋ฐ์ดํฐ๋ฅผ ๋ณด๊ดํ๊ธฐ์ํด ๋ฐฐ์ด์ ๋ฐ์ดํฐ๋ฅผ ์ง์ด ๋ฃ์์ต๋๋ค. ํ์ง๋ง ๋ฐ์ดํฐ๋ค์ ์ข๋ ํจ์ฉ์ฑ ์๊ฒ ๊ด๋ฆฌ ํ๊ณ ์ถ์ต๋๋ค.
[
{
id: 1,
title: 'first video',
description: 'This is first video',
view: 24
},
{
id: 2,
title: 'second video',
description: 'This is second video',
view: 17
},
{
id: 3,
title: 'third video',
description: 'This is third video',
view: 15
},
];
์ด๋ ๋ฐฐ์ด์์ ๋ฐฐ์ด๋ก ์ ๋ฆฌ๋ฅผ ํ๊ธฐ๋ณด๋ค ๊ฐ์ฒด๋ฅผ ์ง์ด ๋ฃ์ด key์ property๋ก ๊ด๋ฆฌ ํ๋ ๊ฒ์ด ๋ ํจ์ฉ์ฑ์ด ์์ต๋๋ค.
๐์์ฑ ์ฝ๋
function convertArrayToObject(arr){
let newArr = [];
for(const prop of arr){
let newObj = {};
prop.forEach(element => {
newObj[element[0]] = element[1]
});
newArr.push(newObj);
}
return newArr;
}
์ฝ๋ ํด์
์ ๋ ฅ๋ฐ์ ๋ฐฐ์ด์ for ...of ๋ฌธ์ ํตํด prop์ ๋ฐฐ์ด์์ ์๋ ๋ฐฐ์ด์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ต๋๋ค.
for (const prop of arr){
let newObj = {};
console.log(prop);
}
/* output
[
[ 'id', 1 ],
[ 'title', 'first video' ],
[ 'description', 'This is first video' ],
[ 'view', 24 ]
]
...
*/
prop๋ฅผ forEach๋ฌธ์ ํตํด ๋ฐฐ์ด์ ๊ฐ ์์๋ฅผ ๊ฐ์ ธ์ต๋๋ค.
for(const prop of arr){
let newObj = {};
prop.forEach(element => {
console.log(element);
console.log('-------');
}
}
/* output
[ 'id', 1 ]
------
[ 'title', 'first video' ]
------
[ 'description', 'This is first video' ]
------
[ 'view', 24 ]
------
...
*/
element์ ๋ด๊ฒจ ์๋ ๋ฐฐ์ด์ ์ธ๋ฑ์ค ๊ฐ์ผ๋ก ํ์ฌ๊ธ newObj ์ ๊ฐ์ฒด๋ฅผ ์ถ๊ฐํฉ๋๋ค.
for(const prop of arr){
let newObj = {};
prop.forEach(element => {
newObj[element[0]] = element[1]
// newObj['id'] = '1';
// ...
// newObj['view'] = 24;
}
}
element๊ฐ prop ๋ฐ์ดํฐ ๋งํผ ์ํ๋ฅผ ํ์ ๊ฒฝ์ฐ forEach๋ฅผ ์ข ๋ฃํ๊ณ newArr์ ์ถ๊ฐํ newObj๋ฅผ push ํฉ๋๋ค.
let newArr = [];
for(const prop of arr){
let newObj = {};
prop.forEach(element => {
newObj[element[0]] = element[1]
});
newArr.push(newObj);
console.log(newObj);
/* output
{
id: 1,
title: 'first video',
description: 'This is first video',
view: 24
}
*/
}
์ด ์์ ์ prop๊ฐ arr์ Symbol.iterator ์์ฑ์ด ์๋ ์ปฌ๋ ์ ์์ ๊ฐฏ์ ๋งํผ ๋ฐ๋ณตํฉ๋๋ค.
๐๏ธ์์๋
๋ฐ์ดํฐ ์ ๊ทผ์ฑ ๋น๊ต
์ฒซ๋ฒ์งธ ์์์ ํ์ดํ์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ง๊ณ ์ค๊ณ ์ถ์ต๋๋ค.( 'first video' )
๋ฐฐ์ด์์ ๋ฐฐ์ด์ผ ๊ฒฝ์ฐ
console.log(videoList[0][1][1]) // output: 'first video'
๋ฐฐ์ด์์ ๊ฐ์ฒด์ผ ๊ฒฝ์ฐ
console.log(videoList[0].title) // output: 'first video'
๋ฐฐ์ด์์ ๋ฐฐ์ด์ผ ๊ฒฝ์ฐ ํ์ฌ ๊ฐ์ง๊ณ ์๋ ๋ฐ์ดํฐ์ ์ ๋ณด๋ฅผ ๋ชจ๋ฅด๋ฉด ์ด๋ ๋ถ๋ถ์ ์ ๊ทผํ๋์ง ์์ธํ ์๊ธฐ ์ด๋ ต์ต๋๋ค. ํ์ง๋ง ๋ฐฐ์ด์์ ๊ฐ์ฒด์ผ ๊ฒฝ์ฐ๋ ๋ด๊ฐ ๋ฌด์์ ๊ฐ์ ธ์ค๊ณ ์ ํ๋์ง ์ง๊ด์ ์ผ๋ก ์์ ์์ต๋๋ค.
* ํ๋ฆฐ ๋ถ๋ถ์ด ์์ผ๋ฉด ์ธ์ ๋ ํผ๋๋ฐฑ ๋ถํ๋๋ฆฝ๋๋ค.
'JavaScript > JS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๊ฐ์ฒด ๋ฆฌํฐ๋ด ๋ชจ๋ ํจํด , ํด๋ก์ ํจํด, ์ฑ๊ธํค ํจํด (0) | 2021.10.05 |
---|