简体   繁体   中英

Dynamic Variable name construction in JS using Lodash or ES6

Instead of referring fields[0] fields[1] , Someone help me to construct dynamically.

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

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

Here is what you are doing right now:

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

If the number of fields is unknown, you can use 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()
  })
}

If what you are actually tryna do is merge a document fragment contained in body to a particular point in the doc , then push is not the right method.

It isn't elegant, but I am pretty sure that this is what you're wanting to get done.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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