通过计算属性返回数组对象中的最后一项?



我正在尝试创建一个计算属性,该属性将仅返回字符串中的文件名(基本上,仅返回数组中的最后一项(

我有一个名为attachments的数据对象,如下所示:

{"abcAttachments":["abc/2019/301902007/acme.pdf","abc/2019/201123007/abc.pdf"],"attachments":["attachments/2019/2da007/hello.png","attachments/2019/2320002007/blue.png"]}

我想做的是只返回上述数组对象中的文件名,而不是文件名的整个路径。例如,只是acme.pdf而不是abc/2019/301902007/acme.pdf

因此,我尝试执行以下计算属性:

filenames() {
const files = this.attachments.attachments
const newArr = files.map(x => x.split('/'))
return newArr[newArr.length - 1]
}

上面的代码不仅返回最后一项(它列出了所有项目(。关于如何使其工作的任何提示?

您需要稍微修改map函数:

请参阅 JSFiddle: https://jsfiddle.net/bwrymeha/

var obj = {"abcAttachments":["abc/2019/301902007/acme.pdf","abc/2019/201123007/abc.pdf"],"attachments":["attachments/2019/2da007/hello.png","attachments/2019/2320002007/blue.png"]};
let result = obj.attachments.map((item) => {
// First split using '/', then return the last item of that split
// which should be the filename.
let split = item.split('/');
return split[split.length - 1];
});
alert(result);
// returns ['hello.png','blue.png']

如果您只需要所有附件中的文件名,则需要执行以下操作:

filenames() {
const result = []
const files = this.attachments
Object.keys(files).forEach(key => {
// Here we have "abcAttachments" and "attachments" as "key"
files[key].map(file => {
// Split every file by '/'
const arr = file.split('/')
if (arr.length) {
result.push(arr[arr.length - 1])
}
})
})
return result
}

最新更新