본문 바로가기
JavaScript/JS & TS

Javascript array 조작 (Firebase)

by noddu 2022. 11. 7.
728x90
반응형

 

function getSentence(data) {
    return new Promise(resolve => {
        const charData = [];
        db.collection(data).orderBy('ch_name').limit(25)
            .get()
            .then((r) => {
                r.forEach((doc) => {
                    charData.push(doc.data().ch_sentence)
                })
                resolve(charData);
            })
            .catch(error => {
                res.send(error.message)
            })
    })
}

charData가 push로 합쳐지지만,
각각 foreach문을 거칠 때마다 새로운 배열이 생성된다

 

function getSentence(data) {
    return new Promise(resolve => {
        const charData = [];
        db.collection(data).orderBy('ch_name').limit(25)	// 25개만
            .get()
            .then((r) => {
                r.forEach((doc) => {
                    charData.push(...doc.data().ch_sentence)	// 전개 연산자
                })
                resolve(charData);	// Promise 성공
                console.log(charData)
            })
            .catch(error => {
                res.send(error.message)
            })
    })
}

push와 spread operator(전개 연산자)를 한번에 사용해
배열이 하나로 합쳐지도록 한다.

반응형