2017-07-26 32 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/ –

相关问题