How split each item inside an Array String - node.js

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

Related

Retrieving data from objects with a variable in nodejs

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

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> = [];

Using Node.js iterating array of object and if value matched then insert all related values in different array

INPUT
[
{"Id":1,"text":"Welcome","question":"san","translation":"willkommen."},
{"Id":1,"text":"Welcome","question":"se","translation":"bienvenida"},
{"Id":1,"text":"Welcome","question":"fr","translation":"propriétaires"},
{"Id":1,"text":"ajax","question":"san","translation":"ommen."},
{"Id":1,"text":"ajax","question":"se","translation":"bienve"},
{"Id":1,"text":"ajax","question":"fr","translation":"propires"}
]
if question = san then all "san" objects will be inserted in array like and so on-
san:[{"text":"Welcome","question":"san","translation":"willkommen.},
{"text":"ajax","question":"san","translation":"ommen."},
se:[{"text":"Welcome","question":"se","translation":"bienvenida.},
{"text":"ajax","question":"se","translation":"bienve."},
fr:[{"text":"Welcome","question":"fr","translation":"propriétaires.},
{"text":"ajax","question":"fr","translation":"propires."},
Question is how do i check if question=san then make one array and insert all san values in it and so on without hardcoding the question property values.
Tried looping things but how to match without hardcoding because in future question attribute can change .
question="san" will be all together in an array "se" will be all together in an array and so on.
New to this not know much about nodejs.
Tried something like this but not coming as required way
fs.readFile('./data.json', 'utf8', function (err,data) {
data = JSON.parse(data);
var array = [];
for(var i = 0; i < data.length; i++) {
var lang = data[i].language;
for(var j= 0; j< data.length; j++) {
if(lang == data[j].language){
array.push(data[j].language);
array.push(data[j].translation);
array.push(data[j].text);
}
}
}
output Required
san:[{"text":"Welcome","question":"san","translation":"willkommen.},
{"text":"ajax","question":"san","translation":"ommen."},
se:[{"text":"Welcome","question":"se","translation":"bienvenida.},
{"text":"ajax","question":"se","translation":"bienve."},
fr:[{"text":"Welcome","question":"fr","translation":"propriétaires.},
{"text":"ajax","question":"fr","translation":"propires."},
I recommend you to use ES6 functions instead of for. You can separate the different processes and make the code more modular and declarative. This way you can change easily the desired output since your code is made by little pieces.
const data = [
{"Id":1,"text":"hi all present ","language":"sde","translation":"Hernjd ndjjsjdj"},
{"Id":1,"text":"hi all present","language":"ses","translation":"dfks kdfk kdfk"},
{"Id":1,"text":"hi all present","language":"sfr","translation":"bsh kkoweofeo"},
{"Id":1,"text":"hi all present","language":"szh","translation":"kdijo keow"},
{"Id":1,"text":"activated","language":"sde","translation":"Konto eid ke"},
{"Id":1,"text":"activated","language":"ses","translation":"La cueweffewfefwef."},
{"Id":1,"text":"activated","language":"sfr","translation":"Cowefrwef"},
{"Id":1,"text":"activated","language":"szh","translation":"fhewjhfwh"},
{"Id":1,"text":"completed","language":"sde","translation":"Ihr fwejiewf"},
{"Id":1,"text":"completed","language":"ses","translation":"Ya hfuwifrw"},
{"Id":1,"text":"completed","language":"sfr","translation":"Votrkwfwe"},
{"Id":1,"text":"completed","language":"szh","translation":"dmksfkwkf"},
{"Id":1,"text":"ACTION","language":"sde","translation":"AKTION"},
{"Id":1,"text":"ACTION","language":"ses","translation":"ACCIONES"},
{"Id":1,"text":"ACTION","language":"fr","translation":"ACTION"}];
// Define the properties that we want to filter for each element
const filterProperties = (item) => ({
text:item.text,
language: item.language,
translation:item.translation
})
// Given a type of languages ('sde'), filter the data in function of this value
const getItemsByLanguage = (language) => {
return data.filter((item) => item.language === language)
}
const onlyUnique = (value, index, self) => {
return self.indexOf(value) === index;
}
// Get the unique values of languages: ['sde', 'ses', 'sfr', ...]
const uniqueLanguages = data.map((item) => item.language).filter(onlyUnique)
// Get all found items for a language ('sde') and get the desired format (returns array of objects)
const resultArray = uniqueLanguages.map((language) => (
{[language]: getItemsByLanguage(language).map(filterProperties)}
))
// Convert the array of objects to single object
const result = Object.assign({}, ...resultArray)
console.log(result)
const data = [
{"Id":1,"text":"hi all present ","language":"sde","translation":"Hernjd ndjjs
jdj"},
{"Id":1,"text":"hi all present","language":"ses","translation":"dfks kdfk
kdfk"},
{"Id":1,"text":"hi all present","language":"sfr","translation":"bsh kkowe
ofeo"},
{"Id":1,"text":"hi all present","language":"szh","translation":"kdijo keow"},
{"Id":1,"text":"activated","language":"sde","translation":"Konto eid ke"},
{"Id":1,"text":"activated","language":"ses","translation":"La cueweffewfef
wef."},
{"Id":1,"text":"activated","language":"sfr","translation":"Cowefrwef"},
{"Id":1,"text":"activated","language":"szh","translation":"fhewjhfwh"},
{"Id":1,"text":"completed","language":"sde","translation":"Ihr fwejiewf"},
{"Id":1,"text":"completed","language":"ses","translation":"Ya hfuwifrw"},
{"Id":1,"text":"completed","language":"sfr","translation":"Votrkwfwe"},
{"Id":1,"text":"completed","language":"szh","translation":"dmksfkwkf"},
{"Id":1,"text":"ACTION","language":"sde","translation":"AKTION"},
{"Id":1,"text":"ACTION","language":"ses","translation":"ACCIONES"},
{"Id":1,"text":"ACTION","language":"fr","translation":"ACTION"}];
// Define the properties that we want to filter for each element
const filterProperties = (data) => ({
text:data.text,
question: data.question,
translation:data.translation
})
// Given a type of question ('san'), filter the data in function of this value
const getQuestions = (question) => {
return data.filter((item) => item.question === question)
}
const onlyUnique = (value, index, self) => {
return self.indexOf(value) === index;
}
// Get the unique values of questions: ['san', 'se', 'fr']
const uniqueQuestions = data.map((item) => item.question).filter(onlyUnique)
// Get all found values for a question and get the desired format (returns
array of objects)
const resultArray = uniqueQuestions.map((question) => (
{[question]: getQuestions(question).map(filterProperties)}
))
// Convert the array of objects to single object
const result = Object.assign({}, ...resultArray)
console.log(result)

Write to json file in increments of 50

I am currently looping through a json object with the purpose of writing certain key value pairs to a new json file. I can write all the elements in the newVideos array to a new file. However, I need to get the first 50 and write it to a file, then the next 50 and so on... Can anyone point me in the right direction?
async function GetVideos(videoData) {
var videos = videoData.videos;
var newVideos = [];
for (var i = 0; i < videos.length; i++) {
var o = videos[i];
newVideos[i] = {
ID: o.ID,
Videos: o.Videos
};
}
}

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.

Resources