2017-07-26 69 views
0

我是新來的node.js和JavaScript,所以這個問題可能很簡單,但我不明白。如何獲取數組Node.js中的最後一項?

我有一個數組中的很多項目,但只想獲得最後一個項目。我試圖使用lodash,但它不知道如何提供數組中的最後一項。

我的陣列看起來像現在這樣:

images : ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', ..., 'jpg.item_n'] 

,我想:

images : 'jpg.item_n' 

使用lodash我越來越:

images : ['g.item_1', 'g.item_2', 'g.item_n'] 

它看起來像只是我以jpg獲得最後一個字母,即'g'。

使用lodash我的代碼如下所示:

const _ = require('lodash'); 
 

 
return getEvents().then(rawEvents => { 
 

 
    const eventsToBeInserted = rawEvents.map(event => { 
 
    return { 
 

 
     images: !!event.images ? event.images.map(image => _.last(image.url)) : [] 
 

 
    } 
 
    }) 
 
})

回答

4

您的問題是您在map內部使用_.last。這將獲得當前項目中的最後一個字符。你想獲得實際Array的最後一個元素。

你可以用pop()做到這一點,但是應該注意它是破壞性的(將從數組中刪除最後一項)。

無損香草溶液:

var arr = ['thing1', 'thing2']; 
console.log(arr[arr.length-1]); // 'thing2' 

或者,與lodash

_.last(event.images); 
+0

我明白了,這很有道理。但是當我想要在eventsToBeInserted中得到結果時,我該如何去解決它? –

1

使用.pop()陣列方法

var images = ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', 'jpg.item_n']; 
 

 
var index= images.length - 1; //Last index of array 
 
console.log(images[index]); 
 

 
//or, 
 

 
console.log(images.pop())// it will remove the last item from array

+0

這會刪除該項目,但他不應該。 – NikxDa

+0

@NikxDa正確。沒有想到這一點。感謝您指點。 – Ved

-1

雖然Array.prototype.pop檢索陣列的最後一個元素它也從陣列移除這個元素。所以應該結合Array.prototype.popArray.prototype.slice

var images = ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', 'jpg.item_n']; 

console.log(images.slice(-1).pop()); 
+0

任何關於downvote的評論? :) –

+0

我做到了這一點:'圖像:! event.images? event.images.map(image => image.url.slice(-1).pop()):[]'但是現在我得到一個錯誤,說'TypeError:image.url.slice(...)。pop不是功能「。不確定那是什麼意思? –

+0

@BjarkeAndersen,最有可能是因爲'event.images'數組格式錯誤。確保'image.url'也是一個數組。我已經爲你準備了一個工作示例:https://jsfiddle.net/enzam28p/ –

相關問題