繁体   English   中英

使用 Lodash 或 ES6 在 JS 中构建动态变量名称

[英]Dynamic Variable name construction in JS using Lodash or ES6

而不是引用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()
    })
}

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

// 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的特定点,那么 push 不是正确的方法。

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

 // 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(); }); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM