2016-12-16 67 views
0

我有一個函數返回的陣列看起來像這樣:想要將輸出到一個數組的NodeJS

.then(Cause.findOne(causeId).populate('admins').exec(function (err, cause) { 

var ids = cause.admins.map(function(admin) { 
    return admin.id; 
}) 
    var join_ids = "'" + ids.join("','"); 

的console.log(join_ids)的輸出;

'26c14292-a181-48bd-8344-73fa9caf65e7','64405c09-61d2-43ed-8b15-a99f92dff6e9','bdc034df-82f5-4cd8-a310-a3c3e2fe3106' 

我試圖到所述陣列的所述第一值傳遞到另一個函數作爲用戶標識過濾器:

let message = { 
    app_id: `${app_id}`, 
    contents: {"en": "Yeah Buddy," + Cause.name + "Rolling Like a Big Shot!"}, 
    filters: [{'field': 'tag', 'key': 'userId', 'relation': '=', 'value': `${join_ids}`}] 

和的console.log的輸出(消息);

{ app_id: '*****************', 
    contents: { en: 'Yeah Buddy,undefinedRolling Like a Big Shot!' }, 
    filters: 
    [ { field: 'tag', 
     key: 'userId', 
     relation: '=', 
     value: '\'26c14292-a181-48bd-8344-73fa9caf65e7\',\'64405c09-61d2-43ed-8b15-a99f92dff6e9\',\'bdc034df-82f5-4cd8-a310-a3c3e2fe3106' } ], 
    ios_badgeType: 'Increase', 
    ios_badgeCount: 1 } 

如果我把console.log(join_ids [0]);

2 

console.log(message);

 { app_id: '*****************', 
    contents: { en: 'Yeah Buddy,undefinedRolling Like a Big Shot!' }, 
    filters: 
    [ { field: 'tag', 
     key: 'userId', 
     relation: '=', 
     value: 2} ], 
    ios_badgeType: 'Increase', 
    ios_badgeCount: 1 } 

我的問題是如何打開join_ids的輸出,其中指數0,1,2,3成爲一個數組。

I.E.

join_ids[0] = '26c14292-a181-48bd-8344-73fa9caf65e7', join_ids[1] = '64405c09-61d2-43ed-8b15-a99f92dff6e9' 

謝謝!

+0

要將數組序列化爲字符串,可以使用['JSON.stringify'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify )。要將其轉換回數組,請使用['JSON.parse'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)。 – qxz

回答

1

根據你的第二個代碼片段,它看起來像它已經是一個數組。證實了這一點,你可以嘗試CONSOLE.LOG如下:

console.log(join_ids.length) // if this returns zero-based length then its an array 

console.log(typeof(join_ids)) // get the TYPE of the variable 

console.log(join_ids[0]) // see if you can address the FIRST value individually 


// for each loop over the array and console out EACH item in the array 
for (var i = 0; i < join_ids.lenght; i++) { 
    console.log(join_ids[i]); 
} 

如果你發現它是一個字符串,我會在逗號後,除去撇號

yourstring = yourstring.replace(/'/g, "") // replaces all apostrophes 

和空間(如果存在)那麼只需用雙引號將值包起來並做

join_ids = join_ids.split(','); // makes the comma separated values an array 

Fiddle example here

+0

對不起,我不認爲我的問題很清楚。輸出爲數組格式,我只想要第一個值爲join_ids [0] ='26c14292-a181-48bd-8344-73fa9caf65e7',join_ids [1] ='64405c09-61d2-43ed-8b15-a99f92dff6e9' – user2019182

+0

只是添加了一個應該幫助的部分...它看起來像一個STRING ...所以使用正則表達式來刪除所有的撇號,並且只剩下一個用逗號分隔的字符串值...然後執行join_ids.split(' ,')...這將使join_ids [0]成爲第一個完整值(第一個逗號前的項目或位置0處的數組值)。這有幫助嗎? – tamak

+0

也可以看到我剛剛添加的JS小提琴鏈接,我在這裏說明清理字符串,轉換爲數組,然後只抓取其中一個數組項。 – tamak