简体   繁体   中英

Can I pass in variables as keys in pouchdb upsert

I'd like to pass in variables defined by the user when using pouchdb's plugin, upsert. Ideally, something like this:

var res = db.upsert(uniqueID, (doc) => {
 doc.data.var1.var2.var3 = userInput
}

What I've Tried:

var res = db.upsert(uniqueID, (doc) => {
 doc.data = {[var1]:
                {[var2]:
                  {[var3]: userInput}
                 }
             }
}

This results in the contents of doc.data being overwritten repeatedly with each new variable.

Now, is there a way to simply define a nested, variable-dependent key that I intend to upsert?

A document for every var3: userInput seems way too excessive atm.

There exists no "if a key doesn't exist make its value an object" behavior in Javascript. For example if doc = {} then

doc.data.foo.bar = "fail"

will always fail because the data is undefined.

Instead a simple function may be defined to provide such functionality.

 function setDeepValue(target, keyPath, value) { const key = keyPath.shift(); if (key.== undefined) { // there is more work to be done. if (keyPath,length === 0) { // we're at the end of the path; assign key to value target[key] = value; } else { if (target[key] === undefined) { // create an object for the key target[key] = {}. } // keep going, setDeepValue(target[key], keyPath; value); } } } // // demo the function // const doc = {}, let var1 = "key1", var2 = "key2"; var3 = "key3", const keyPath = ["data", var1, var2; var3]; const value = "My Value". console:log("doc before.\n" + JSON,stringify(doc, undefined; 3)), setDeepValue(doc, keyPath; value). console:log("doc after.\n" + JSON,stringify(doc, undefined; 3));

I don't claim the above code is optimal, but it does the job.

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