Im trying to get a field from a "doc.data" using a variable, the thing is that i want to reuse that function with different field names.
This is the code:
btnsEditvalue.forEach((btn) => {
btn.addEventListener("click", async (e) => {
try {
propToEdit = e.target.dataset.prop;
const doc = await getElement(e.target.dataset.id, col);
const element = doc.data();
console.log(element.propToEdit)
editElement.value = element.e.target.dataset.prop;
id = doc.id;
}
catch {
console.log("error");
}
});
});
The output is undefined, because "propToEdit" isnt a field in my database.
You can try passing the dynamic key using the bracket notation, instead of the dot notation.
Refer to javascript object property accessors.
const element = doc.data()
const ELEMENT_KEY: string = 'propToEdit'
console.log(element[ELEMENT_KEY])
You can access fields dynamically with a custom name
fieldName = "stringValue"
element[fieldName]
this does depend entirely on where doc from doc.data() is maintained
You can wrap it into a function as well, this will return the value or null.
You can swap null out with any other default value you want.
function getField(fieldName, doc){
return doc.data()[fieldName] || null;
}
Related
I am trying to create a method that returns a JSON object for custom headers to use with HTTPS requests. This should be defined as customHeaders={{headerKey: 'headerValue'}}
I am new to JSX and a little confused with my implementation of forEach loop here.
Here, this.props.httpHeaders passes a list of Keys and Values. The key is this.props.headerKey and corresponding value this.props.headerValue
The expected return is an Object that holds the key value pairs as {headerKey: 'headerValue'}
Here's my not so correct implementation. Can anyone explain me how to implement forEach() here? Thanks
getCustomHeaders = () => {
var customHeaders;
let keyValueStr = "";
if (this.isStatusAvailable(this.props.httpHeader) && this.isStatusAvailable(this.props.restURL)) {
// Building Custom Headers input string
this.props.httpHeader?.items?.forEach((element) => {
const attrKey = this.props.headerKey.get(element);
const attrValue = this.props.headerValue.get(element);
if (keyValueStr !== "") {
keyValueStr = keyValueStr.concat(",");
}
keyValueStr = keyValueStr+attrKey.value+": "+"'"+attrValue.value+"'";
});
}
customHeaders = JSON.parse("{" + keyValueStr + "}");
return customHeaders;
};
I have to get the client_id from an api call which would be available in body.
const oauthClients = [
{ "0ADAA2B8": "96eb8c0fbfb31ac43288" },
{ P3CKTGC7: "FKC78N6Plm1Vwjk8KItS" },
];
const client_id = JSON.parse(JSON.stringify(req.body.client_id));
const filtered_value = oauthClients.find((ele) => {
return (ele.client_id = client_id);
});
console.log(filtered_value);
I have tried like return ${ele}+.+`${req.body.client_id}
Anyone please help..!
You need to use the strict equality operator instead
const filtered_value = oauthClients.find((ele) => {
return ele.client_id === client_id;
});
Also oauthClients us an object so you can't really traverse it using .find and access ele.client_id, you will need to somehow take the object values and traverse them in an array like fashion
e.g. using Object.keys() :
const filtered_value = Object.keys(oauthClients).find((key) => {
return oauthClients[key] === client_id;
});
What makes this a bit hard is that your original data isn't really well structured:
Given this:
const oauthClients = [
{ "0ADAA2B8": "96eb8c0fbfb31ac43288" },
{ P3CKTGC7: "FKC78N6Plm1Vwjk8KItS" },
];
There's no "client_id" field - the client ID is the field name, so its hard to parse. In Javascript, to get generic access to the keys and values of a dictionary, you use the Object.keys() and Object.values() functions.
I think you're looking to get the token given the client ID, so something like this:
/**
* Returns the token for the given client ID or undefined if it isn't found
*/
function findToken(clientId: string) {
const foundElement = oauthClients.find(e => Object.keys(e)[0] === clientId)
return foundElement
? Object.values(foundElement)[0]
: undefined
}
I have written the below code
updatePublication(projectName, publicationId, publicationObj, callback) {
let self = this;
this.initDatabase(function (db) {
let tx = self.db.transaction(self.PUBLICATIONS, self.READ_WRITE);
let store = tx.objectStore(self.PUBLICATIONS);
let index = store.index(self.PROJECT_NAME);
let request3 = index.openCursor(IDBKeyRange.only(projectName));
console.log("hrere");
request3.onsuccess = function () {
let cursor = request3.result;
if (cursor) {
let updateObject = cursor.value;
if (updateObject.publicationID == publicationId) {
updateObject.publicationObject = publicationObj;
cursor.update(updateObject);
callback(publicationId);
}
cursor.continue();
} else {
callback(publicationId);
}
};
});
}
But this give error:
I checked the cause of error. It is beacuse , publicationObj which is passed has an object named _requestObjectBuilder which is of the type Subscriber.
used somewhere in the code like this:
_requestObjectBuilder = interval(1000).pipe(tap(() => {}));
Is there any way i can modify my updatePublication code to ignore this value?
Does indexed db support a query for ignoring a value and saving the data?
Note: If i set publicationObj._requestObjectBuilder = undefined, the data gets saved to indexedDB. But this breaks the functionality where _requestObjectBuilder is used.
Fixed the issue by cloning the object and setting it to undefined
let clonedObject = Object.assign({}, publicationObject);
clonedObject._requestObjectBuilder = undefined;
Now i am updating the clonedObject
I am trying to hide elements based on whether the user has added the class numbers to the database which I am retrieving through json data. If all the class numbers are present on the component I want to hide it.
At the moment I keep getting this error:
TypeError: $(...).data(...).split is not a function
export function VisaToggleComponent() {
let json = {
visa_subclass:[462,500,801]
};
let elements = document.querySelectorAll('[data-visa-hide]');
console.log(elements);
$(elements).each(function() {
let data = json.visa_subclass,
target = $(this).data('visa-hide').split(',').map(Number);
console.log(target);
for (let i in data) {
let val = data[i];
let index = target.indexOf(val);
if(index > -1) {
$(this).hide();
}
}
});
}
split is a method of the String object. Since you're getting
TypeError: $(...).data(...).split is not a function
It means $(this).data('visa-hide') is not a string.
To be honest, I didnt try to understand your code, however if you think $(this).data('visa-hide') is string-like data type you have to change $(this).data('visa-hide').split(',') to String.prototype.split.call($(this).data('visa-hide'), ',')
I'm trying to fetch an object 'single Post' within an object 'Posts' from a json file within meteor, which looks like this.
I found an effective way of doing it, using underscore findWhere to get to it. this is the code
_.findWhere(_.findWhere(CategoryCollection.find().fetch(),
{"_id":"CategoryPublication-5"}).posts,{"ID":46});
however when i put this into meteor, i'm getting undefined
this is the code i used
Template.CategoryArticleSingle.helpers({
articles: function () {
var id = FlowRouter.getParam('ID')
var category = FlowRouter.getParam('category')
console.log(CategoryCollection.find().fetch());
let match = _.findWhere(_.findWhere(CategoryCollection.find().fetch(), {"_id":category}).posts,{"ID": id});
console.log("match",id,category,match);
return match;
}
});
Why am i getting undefined
update.
would this be correct? i substituted the 47 id, with just id so i can use it for any link.
Im getting "category" is read-only error.
Template.CategoryArticleSingle.helpers({
articles: function () {
var id = FlowRouter.getParam('ID')
var category = FlowRouter.getParam('category')
console.log(CategoryCollection.find().fetch());
const category = CategoryCollection.find().fetch().find(c => c._id === id);
let post = null;
if (category) {
post = category.posts.find(p => p.ID === id);
}
console.log("post",id,category,post);
return post;
}
});
There's no need to use lodash/underscore's findWhere. This functionality is built into ES2015. Also, you may consider breaking up the code into a few lines to make it more legible.
const category = CategoryCollection.find().fetch().find(c => c._id === 'CategoryPublication-5');
let post = null;
if (category) {
post = category.posts.find(p => p.ID === 47);
}