簡體   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