Retrieving data from objects with a variable in nodejs - node.js

How to get values from an object in nodejs?
let person = {temperature:[35,36],humidity:[85,90,89};
let y = req.query.id; (which is `temperature`)
console.log(person.y);

In order to get values from a nodejs object you can do it in the following way
Getting it directly person.temparature or person[myvar]
Or by iteration:
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`); // key = 'temperature', value = [35,36] for the first entry (temperature)
}
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

Related

How split each item inside an Array String

how can i do a split for each item inside an array of strings ?
i am trying with for, but the typescript acuses Type 'string[]' is not assignable to type 'string'.. I don't know another way to made that.
to contextualize , I am converting the request.files into a JSON , and JSON to Array, and i need the first numbers of the file name , which will be used as an ID to the database
my try with for:
let ids: Array<string> = []; //Array declaration
var myfiles = JSON.parse(JSON.stringify(req.files)) // Convert Request Files to JSON
myfiles.map((item: any) => {
ids.push(item.filename) //Push each file name into the array
})
for(var i = 0; i< ids.length; i++){
ids[i] = ids[i].split('_',1) // Here would change the name of each item inside the array, but it accuses the aforementioned error
}
and my try with foreach, who accuses the same error
ids.forEach((item, index) => {
ids[index] = item.split('_', 1)
})
SOLUTION
as our friend long_hair_programmer suggested, changing ids[i] = ids[i].split('_',1) to ids[i] = ids[i].split('_',1)[0] resolves the problem

error TS2538: Type 'CCCustomer' cannot be used as an index type

For below mentioned code facing error as error TS2538: Type 'CCCustomer' cannot be used as an index type.
with let index in ccCustomerList its working fine but in sonarqube received issue as Use "for...of" to iterate over this "Array". any alternative way available for this.
let data:Array<Customer>;
for (const index of CustomerList) {
const Customer = CustomerList[index];
const List: Array<string> = [];
In your loop, the index variable is not really an index of the array, but it's an object from the Customerlist, this is how for of works and that's why you get the error stating you can't use an object as an index.
So you don't need to get the customer from the CustomerList array since it's already there in your index variable.
Rename index to Customer and remove this line:
const Customer = CustomerList[index];
Replace all CustomerList[index] with Customer in your code.
Example
for (const Customer of CustomerList) {
const guidList: Array<string> = [];
// Use Customer object
More information
Update
If you need to use an index use a regular loop or add Array.entries() to the current loop which returns the index and the value (just remove it if not needed).
Example
for (const [index, value] of CustomerList.entries()) {
const Customer = CustomerList[index];
const guidList: Array<string> = [];

Verify and select the right object in an array thanks to a find method which will match with a param json

I need some help,
I've got a json with some parameters inside of it, actually 2 but one day we may add some more in it.
I want to find between some object in an array the right one thanks to all parameters in the json
Am i using the right method ?
to be clearer, i want the param.t to match with the element.t, and the param.tid to match with the element.tid and if moving forward one more parameter cd1 is added to the JSON, this param.cd1 will match with element.cd1
thanks for the time !
const array1 = [{"t":"pageview","de":"UTF-8","tid":"UA-xxxxxxxxxx-17","cd1":"Without cookie"},{"t":"timing","de":"UTF-8","tid":"UA-xxxxxxxx-1","cd1":"France"}];
const param = { t: 'pageview', tid: 'UA-xxxxxxxxxx-17' }
for (let [key, value] of Object.entries(param)) {
console.log(`${key}: ${value}`);
}
const obj = array1.find(element => element.t == param.t);
If I am following correctly, you want to compare an array of objects to an object and based on some keys in 'param' object you want to filter out your array1.
const array2 = [{"t":"pageview","de":"UTF-8","tid":"UA-xxxxxxxxxx-17","cd1":"Without cookie"},{"t":"timing","de":"UTF-8","tid":"UA-xxxxxxxx-1","cd1":"France"}];
const param1 = { t: 'pageview', tid: 'UA-xxxxxxxxxx-17' }
const test = array2.find(checkExist);
const checkExist = el => {
return el.t == param1.t && el.tid == param1.tid; // here you can add your keys in future
}

Why is array.push() not working correctly?

I have a function which returns an array of dishes from a firestore database.
With console.log I check that the dish I want to push is correctly formatted, then push it.
Finally I console.log the array to check if everything is alright.
Here is what I got:
https://image.noelshack.com/fichiers/2019/05/5/1549048418-arraypush.png
switch (type) {
case "Plats": {
this.nourritureCollection.ref.get().then(data => {
let platArray : Plat[] = [];
data.docs.forEach(doc => {
this.plat.name = doc.data().nourritureJson.name;
this.plat.price = doc.data().nourritureJson.price;
this.plat.ingredients = doc.data().nourritureJson.ingredients;
this.plat.type = doc.data().nourritureJson.type;
this.plat.availableQuantity = doc.data().nourritureJson.availableQuantity;
this.plat.isAvailableOffMenu = doc.data().nourritureJson.isAvailableOffMenu;
this.plat.imgUrl = doc.data().nourritureJson.imgUrl;
this.plat.temp = doc.data().nourritureJson.temp;
console.log(this.plat)
platArray.push(this.plat);
});
console.log(platArray)
return platArray;
});
break;
}...
plat is instantiated within my service component, I couldn't declare a new Plat() inside my function.
The expected result is that dishes should be different in my array of dishes.
You are updating this.plat in every iteration. So it will have n number of references in the array pointing to the same object, therefore, the values for all the array elements will be last updated value of this.plat
What you need is to create new Plat object for every iteration.
data.docs.forEach(doc => {
let plat: Plat = new Plat();
plat.name = doc.data().nourritureJson.name;
plat.price = doc.data().nourritureJson.price;
plat.ingredients = doc.data().nourritureJson.ingredients;
plat.type = doc.data().nourritureJson.type;
plat.availableQuantity = doc.data().nourritureJson.availableQuantity;
plat.isAvailableOffMenu = doc.data().nourritureJson.isAvailableOffMenu;
plat.imgUrl = doc.data().nourritureJson.imgUrl;
plat.temp = doc.data().nourritureJson.temp;
console.log(plat)
platArray.push(plat);
});
As pointed out in the comment, you can only use new Plat() if Plat is a class, if it is an interface, just let plat:Plat; would do.

setting context with list of objects as prameters in dialogflow

I have a list of values each having another KEY value corresponding to it, when i present this list to user, user has to select a value and agent has to call an external api with selected value's KEY. how can i achieve this in dialogflow?
I tried to send the entire key value pair in the context and access it in the next intent but for some reason when i set a list(array) to context parameters dialogflow simply ignoring the fulfillment response.
What is happening here and is there any good way to achieve this? I am trying to develop a food ordering chatbot where the category of items in menu is presented and list items in that menu will fetched when user selects a category, this menu is not static thats why i am using api calls to get the dynamic menu.
function newOrder(agent)
{
var categories = []
var cat_parameters = {}
var catarray = []
const conv = agent.conv();
//conv.ask('sure, select a category to order');
agent.add('select a category to order');
return getAllCategories().then((result)=>{
for(let i=0; i< result.restuarantMenuList.length; i++)
{
try{
var name = result.restuarantMenuList[i].Name;
var catid = result.restuarantMenuList[i].Id;
categories.push(name)
//categories.name = catid
cat_parameters['id'] = catid;
cat_parameters['name'] = name
catarray.push(cat_parameters)
}catch(ex)
{
agent.add('trouble getting the list please try again later')
}
}
agent.context.set({
name: 'categorynames',
lifespan: 5,
parameters: catarray, // if i omit this line, the reponse is the fultillment response with categories names, if i keep this line the reponse is fetching from default static console one.
})
return agent.add('\n'+categories.toString())
})
function selectedCategory(agent)
{
//agent.add('category items should be fetched and displayed here');
var cat = agent.parameters.category
const categories = agent.context.get('categorynames')
const cat_ob = categories.parameters.cat_parameters
// use the key in the catarray with the parameter cat to call the external API
agent.add('you have selected '+ cat );
}
}
The primary issue is that the context parameters must be an object, it cannot be an array.
So when you save it, you can do something like
parameters: {
"cat_parameters": catarray
}
and when you deal with it when you get the reply, you can get the array back with
let catarray = categories.parameters.cat_parameters;
(There are some other syntax and scoping issues with your code, but this seems like it is the data availability issue you're having.)

Resources