【问题标题】:Dynamic Variable name construction in JS using Lodash or ES6使用 Lodash 或 ES6 在 JS 中构建动态变量名称
【发布时间】:2020-02-27 05:53:58
【问题描述】:

不是指fields[0] fields[1],有人帮我动态构造。

//fields =['string1','string2']  

createNestedSubDoc(id, body, fields) {
    return this.model.findById(id).then(doc => {
        doc[fields[0]][fields[1]].push(body)
        return doc.save()
    })
}

【问题讨论】:

  • 你能再解释一下吗?

标签: javascript node.js mongoose lodash


【解决方案1】:

它并不优雅,但我很确定这就是你想要完成的。

// Your current code:
//fields =['string1','string2']  

//createNestedSubDoc(id, body, fields) {
//    return this.model.findById(id).then(doc => {
//        doc[fields[0]][fields[1]].push(body)
//        return doc.save()
//    })
//}

// Lodash solution.
const fields = ['string1', 'string2'];

function createNestedSubDoc(id, body, fields) {
  return this.model.findById(id)
    .then((doc) => {
      const path = _.join(fields, '.');
      const currentPathArray = _.get(doc, path, []);
    
      _.set(doc, path, _.concat(currentPathArray, [body]);
      
      return doc.save();
    });
}

【讨论】:

    【解决方案2】:

    这是你现在正在做的事情:

    // Your code pushes body to the array doc.key1.key2
    // Is that the behaviour you want?
    const doc = {
       key1: {
          key2: []
       }
    }
    
    const fields = ['key1', 'key2']
    
    createNestedSubDoc(id, body, fields) {
        return this.model.findById(id).then(doc => {
            doc[fields[0]][fields[1]].push(body)
            return doc.save()
        })
    }
    

    如果字段数未知,可以使用lodash.pick

    const _ = require('lodash')
    
    createNestedSubDoc(id, body, fields) {
      return this.model.findById(id).then(doc => {
        const arrayPropertyInDoc = _.pick(doc, fields)
          arrayPropertyInDoc.push(body)
          return doc.save()
      })
    }
    

    如果您实际上尝试将包含在body 中的文档片段合并到doc 中的特定点,那么推送不是正确的方法。

    【讨论】:

    • 感谢@Josh Wulf 的回答,但不要担心在我的猫鼬文档中只是我的字段名称的键。我需要我通过应该动态构建的索引引用的字段。 #thanks_in_advance
    • 是的,这就是您的代码所做的。你有什么问题?您想从文档本身获取键名吗?
    • 再次感谢@Josh Wulf,我想我没有明确地暴露我的问题。问题是字段有限制。对?我希望通过数组(字段)传递字符串的数量,以便我应该动态构造这一行doc[fields[0]][fields[1]].push(body) 对吗?
    • 显示arrayPropertyInDoc.push is not a function
    • 感谢您的大力帮助@Josh Wulf
    猜你喜欢
    • 2012-08-30
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 2015-02-27
    • 1970-01-01
    相关资源
    最近更新 更多