代码之家  ›  专栏  ›  技术社区  ›  l2aelba

Lodash:通过给定键联接值

  •  0
  • l2aelba  · 技术社区  · 6 年前

    我正在尝试搜索 洛达什.js 用于通过给定键或其他方式联接值…

    例子:

    const obj = {firstname : 'John', title: 'Mr.', lastname: 'Due'}
    

    预期结果:

    Mr. John Due
    

    任何类似的功能 _.join() 但更好的是,我可以做像……

    _.joinX(obj, ['title', 'firstname', 'lastname'], ' ')
    

    为什么不……?

    obj.title + ' ' + obj.firstname + ' ' + obj.lastname
    

    因为有时候我的目标像…(我不会给出更多的变量)

    obj.current.user.info.title + ' ' + obj.current.user.info.firstname + ' ' + obj.current.user.info.lastname
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Adam Azad    6 年前

    您可以将以下内容移植到Lodash。

    const joinByKeys = (obj = {}, props = [], separator = '') => {
        // empty array.
        let arr = [];
        // push props to array
        props.forEach(p => arr.push(obj[p]))
        // return the joined array.
        return arr.join(separator);
    }
    
    
    const obj = {firstname : 'John', title: 'Mr.', lastname: 'Due'}
    
    console.log( joinByKeys(obj, ['title', 'firstname', 'lastname'], ' ') );
        2
  •  0
  •   l2aelba    6 年前

    我想我明白了:

    const obj = {firstname : 'John', title: 'Mr.', lastname: 'Due'}
    let name = _(obj).pick(['title', 'firstname', 'lastname']).values().join(' ')
    console.log(name)
    

    不是像我预期的那样特别的功能,但必须运行一点lodash的功能