2017-12-30 29 views
-1
내가 을 중포 기지, 의 모든 사용자를 반복하고 특정 PARAMS에서 JSON을 만들려고 해요

의 특성 '푸시'를 읽을 수 없습니다하지만 난이 오류를 얻을 :형식 오류를 해결하는 방법 : 정의되지 않은

TypeError: Cannot read property 'push' of undefined

어떻게 해결할 수 있습니까? 감사합니다.

admin.database().ref("players").once('value', (snapshot, y) => { 

     var jsonArray = '{}'; 

     snapshot.forEach(_child => { 

      let cash = _child.child("player_cash"); 
      let uid = _child.key; 
      let name = _child.child("player_name"); 

      var temp = JSON.parse(jsonArray); 
      temp[uid].push({"id":uid,"cash":cash}); 
      jsonArray = JSON.stringify(temp); 
     }); 

     response.send(jsonArray); 
} 

답변

1

임시 개체는 공백입니다. 해당 요소의 속성에 밀어하려면 먼저 존재 (및 배열로 설정) 여부를 확인해야합니다 여부 :

admin.database().ref("players").once('value', (snapshot, y) => { 

     var jsonArray = '{}'; 

     snapshot.forEach(_child => { 

      let cash = _child.child("player_cash"); 
      let uid = _child.key; 
      let name = _child.child("player_name"); 

      var temp = JSON.parse(jsonArray); 
      temp[uid] = temp[uid] || [];   // <======== 
      temp[uid].push({"id":uid,"cash":cash}); 
      jsonArray = JSON.stringify(temp); 
     }); 

     response.send(jsonArray); 
} 
0

당신이합니다 (jsonArray을 구문 분석하는 대신 그냥 만드는 이유를 잘 모르겠어요 불변성?).
어쨌든 빈 개체이므로 키 내부에 push을 시도합니다. 키가 없으면 키를 만들어야합니다. 아마 당신은이 방법을 수행해야합니다

admin.database().ref("players").once('value', (snapshot, y) => { 

     var jsonArray = '{}'; 

     snapshot.forEach(_child => { 

      let cash = _child.child("player_cash"); 
      let uid = _child.key; 
      let name = _child.child("player_name"); 

      var temp = JSON.parse(jsonArray); 
      temp[uid] = temp[uid] || []; // create the key if its not already there 
      temp[uid].push({"id":uid,"cash":cash}); 
      jsonArray = JSON.stringify(temp); 
     }); 

     response.send(jsonArray); 
} 
0

개체 푸시 방법이 없기 때문에 당신이 점점 오류입니다.

당신은

admin.database().ref("players").once('value', (snapshot, y) => { 
    var jsonArray = {}; 

    snapshot.forEach(_child => { 

     let cash = _child.child("player_cash"); 
     let uid = _child.key; 
     let name = _child.child("player_name"); 

     jsonArray[uid] = {"id":uid,"cash":cash}; 
    }); 

    response.send(jsonArray); 
} 

간단한 일들을 유지할 수 있습니다 이것의 결과는 다음과 같습니다

{ 
    'id_1': { id: 'id_1', cash: 10 }, 
    'id_2': { id: 'id_2', cash: 20} 
} 
이제

난 당신이 결과를 저장하는 대신 객체의 배열을 사용하는 것이 좋습니다 DB의.

admin.database().ref("players").once('value', (snapshot, y) => { 
    var jsonArray = []; 

    snapshot.forEach(_child => { 

     let cash = _child.child("player_cash"); 
     let uid = _child.key; 
     let name = _child.child("player_name"); 

     jsonArray.push({"id":uid,"cash":cash}); 
    }); 

    response.send(jsonArray); 
} 

이의 결과는 다음과 같습니다

[ 
    { id: 'id_1', cash: 10 }, 
    { id: 'id_2', cash: 20} 
] 

이것은 쉽게 처리 할 수있을 것입니다.