【问题标题】:Return last item in an Object of arrays via a computed property?通过计算属性返回数组对象中的最后一项?
【发布时间】:2019-08-08 12:50:24
【问题描述】:

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

我有一个名为 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]
}

上面的代码不只是返回最后一项(它列出了所有的项)。关于如何让它发挥作用的任何提示?

【问题讨论】:

    标签: vuejs2


    【解决方案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']
    

    【讨论】:

    • 这就是我要找的——谢谢!但是,我现在得到一个 Cannot read property 'map' of undefined 。我需要在某处做 async.await 吗?
    • 你可以用if(obj)if(obj.attachments)包装它,然后当你的obj未定义时,计算的属性将返回undefined。或者您可以像data() { return {obj: {attachments:[]}}} 一样预先填写您的数据
    【解决方案2】:

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

    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
    }
    

    【讨论】:

    • 感谢你的贡献
    猜你喜欢
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 2021-02-16
    • 2014-06-18
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多