list of arrays into array of objects - arrays

I have a problem that I can't solve. Here is the thing. As a result of iteration, for each item I get one array with one object inside. I would like it to be one array that has all object items inside in order for further mapping and filtering. Later I'll need it to be json.
console.log(data)
[...][...] ... [...] // result
I want:
{ [...], [...] ... [...] } // this I want
I tried push, join, merge and spread operator without any luck.
code:
const body = [];
const result = await fetch(uls, options);
body.push({
textBody: await result.text(),
url: i.contentUrl,
});
const allAddedHashtags = body
.map((i) => {
const searchFor = /([+]hashtags: [^\n]*(\n+))/g;
return {
hashtags: i.textBody.match(searchFor),
url: i.url,
};
})
.filter((i) => i.hashtags !== null && i.hashtags.length === 2)
.map((i) => {
return {
original: i.hashtags[0]
.replace(/[+]hashtags: "/g, "")
.replace(/"\n/g, "")
.split(",")
.sort(),
edited: i.hashtags[1]
.replace(/[+]hashtags: "/g, "")
.replace(/"\n/g, "")
.replace(/\n/g, "")
.replace(/##/g, "#")
.replace(/ #/g, "#")
.replace(/"#/g, "#")
.replace(/\"/g, "")
.split(",")
.sort(),
url: i.url,
};
})
.map((i) => {
return {
keep: i.edited.filter((x) => !new Set(i.original).has(x)),
url: i.url,
};
});

Related

How to return this local variable in nested functions and "globalize" it?

I am trying to catch some values from a file and put them in an array.
After battling up with conversions and values, I reach my "final" data to return which in my case is arrayFile.I understand that I have nested some functions and now I couldn't return my data properly and globally in the first part of the code, because it displays/returned undefined.
In a few words,how I can retutn this variable specifically or in another variable? Because the console.log works, however just in that block. How could I end my 1st FOR loop and keep the data (arrayFile) global so for being used in other stuff? Any help wuold be precious. Hoping I'm asking questions the right way, thanks for your patience.
const directoryPath = path.join(__dirname, './sample');
//passing directoryPath and callback function
fs.readdir(directoryPath, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function (file) {
arrayNomi.push(file);
});
for(i=0;i<arrayNomi.length;i++){
leggiFile(arrayNomi[i],arrayDati)
}
});
function leggiFile(nomeFile,arrayFile){
const xmlFile = fs.readFile(nomeFile,{encoding:'utf8', flag:'r'},
function(err, data) {
if(err)
console.log(err);
else
convert.parseString(data, (err, result) => {
if(err) {
throw err;
}
// `result` is a JavaScript object
// convert it to a JSON string
//const json = JSON.stringify(result, null, 4);
//console.log(json)
// log JSON string
//console.log(json);
// method to collect string values
const collectAllValues = (arr, res = []) => {
// append result "res" with any "string" elt in array "arr"
const r = [
...res,
...(
arr?.filter(
elt => typeof elt !== 'object'
) ?? []
)
];
// filter out "arr" elements that are "objects"
const nx = arr?.filter(
elt => typeof elt === 'object'
) ?? [];
// if "objects" exist in "arr" elements-list
// use ".reduce()" to iterate over the filtered "arr"
// then, for each object, use ".reduce()" to
// iterate over values that are arrays and make
// recursive call to this method & return the value
if (nx && nx.length) {
return (
nx.reduce(
(acc, ob) => ([
...acc,
Object.values(ob)
.filter(v => v && Array.isArray(v))
.reduce((ac2, ar) => ([...ac2, ...collectAllValues(ar)]), acc)
.flat()
]),
r
)
);
} else return r;
// if no "objects" exist, simply return earlier
// result "r"
};
console.log(
'collect all values:\n',
Object.values(result["p:FatturaElettronica"])
.filter(v => v && Array.isArray(v))
.reduce((acc, ar) => ([...acc, ...collectAllValues(ar)]), [])
.flat()
);
var jsonDatiTabella = {};
var dati = [];
jsonDatiTabella.dati = dati;
var tipoDocumento= result["p:FatturaElettronica"].FatturaElettronicaBody[0].DatiGenerali[0].DatiGeneraliDocumento[0].TipoDocumento[0];
var dataDocumento= result["p:FatturaElettronica"].FatturaElettronicaBody[0].DatiGenerali[0].DatiGeneraliDocumento[0].Data[0];
var importo = result["p:FatturaElettronica"].FatturaElettronicaBody[0].DatiGenerali[0].DatiGeneraliDocumento[0].ImportoTotaleDocumento[0];
var prestatore= result["p:FatturaElettronica"].FatturaElettronicaHeader[0].CedentePrestatore[0].DatiAnagrafici[0].Anagrafica[0].Denominazione[0];
var committente= result["p:FatturaElettronica"].FatturaElettronicaHeader[0].CessionarioCommittente[0].DatiAnagrafici[0].Anagrafica[0].Nome[0];
var tempDati = {
"TipoDoc": tipoDocumento,
"DataDoc": dataDocumento,
"Importo":importo,
"CedentePrestatore" :prestatore,
"CessionarioCommittente":committente
}
jsonDatiTabella.dati.push(tempDati);
console.log(jsonDatiTabella);
arrayFile.push(tempDati.TipoDoc,tempDati.DataDoc,tempDati.Importo,tempDati.CedentePrestatore,tempDati.CessionarioCommittente)
console.log("arrayFile:" + arrayFile)
});
});
}

Loop through 2 select options and show API best match

I want to show the best results (of "plants") from my 2 select options: "sunlight" and "water". API console.log is in the code: https://jsfiddle.net/Luckzzz/1p8bk0g5/
I want to show plants based on the combination of these 2 select options..
const url = 'https://front-br-challenges.web.app/api/v2/green-thumb/?sun=high&water=regularly&pets=false';
let sunlight = $('#sunlight');
sunlight.empty();
sunlight.append('<option selected="true" disabled>Choose sunlight</option>');
sunlight.prop('selectedIndex', 0);
let water = $('#water');
water.empty();
water.append('<option selected="true" disabled>Choose water amount</option>');
water.prop('selectedIndex', 0);
$.getJSON(url, function (data) {
console.log(data);
$.each(data, function (key, entry) {
// Populate SUNLIGHT dropdown:
sunlight.append($('<option></option>')
.attr('value', entry.abbreviation)
.text(entry.sun));
// Populate WATER dropdown:
water.append($('<option></option>')
.attr('value', entry.abbreviation)
.text(entry.water));
})
});
Not sure if I understood your question correctly. You can check this fiddle.
const url = 'https://front-br-challenges.web.app/api/v2/green-thumb/?sun=high&water=regularly&pets=false';
let selectedSun, selectedWater, globalData = [];
let sunlight = $('#sunlight');
sunlight.empty();
sunlight.append('<option selected="true" disabled>Choose sunlight</option>');
sunlight.prop('selectedIndex', 0);
let water = $('#water');
water.empty();
water.append('<option selected="true" disabled>Choose water</option>');
water.prop('selectedIndex', 0);
sunlight.on('change', function() {
selectedSun = this.value;
showImages();
});
water.on('change', function() {
selectedWater = this.value;
showImages();
});
const showImages = () => {
$("#items").empty();
globalData.forEach(item => {
if (!selectedWater || (selectedWater && item.water === selectedWater) &&
(!selectedSun || (selectedSun && item.sun === selectedSun))) {
let img = document.createElement('img');
img.src = item.url;
$("#items").append(img);
}
})
}
$.getJSON(url, function (data) {
console.log(data);
globalData = data;
const sunlights = data.reduce((acc, curr) => {
if (!acc.includes(curr.sun)) acc.push(curr.sun)
return acc;
}, []);
const waterTypes = data.reduce((acc, curr) => {
if (!acc.includes(curr.water)) acc.push(curr.water)
return acc;
}, []);
$.each(sunlights, function (key, entry) {
sunlight.append($('<option></option>')
.attr('value', entry)
.text(entry));
})
$.each(waterTypes, function (key, entry) {
water.append($('<option></option>')
.attr('value', entry)
.text(entry));
})
});
In short, I:
reduced those two lists, so you don't have duplicated
added method to show images, when one of selects changes

An empty array is returned when calling $http.get it within a service [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I want to get the name from an array that is being generated from $http.get, however this is returning an empty array. When i do a console it see the array populated however when i loop inside the array to get the value of name property based on whether an id is equal to a certain, the array is empty.
In my controller i have a service call that shall return the name value.
var params = { Id: $scope.Id, SettingId: $scope.SettingId };
$scope.selectedUserName = helloService.getSelectedUserName($scope.UserId, params);
In my service
I have used the getUserList function to populate the list of user in a dropdown and it works by generating the array with the values.
However When i got another page , i want to be able to display the name of the selected user, so I wanted to use the same getUserList function to retrieve the name
this.getUserList = function (val) {
var usersObj = [];
var url = "/api/v1/hello/getusers";
var params = { Id: val.Id, SettingId: val.SettingId };
var config = { params: params };
var promise = $http.get(url, config)
.then(function (response) {
angular.forEach(response.data, function (key, value) {
angular.forEach(key, function (k, index) {
usersObj[index] = ({ userId: k.userId, name: k.name});
});
});
},
function errorCallback(response) {
console.log("Unable to perform get request");
throw response;
});
var usersList = usersObj;
return usersObj;
};
this.getSelectedUserName = function (id, param) {
var name = "";
var userList =this.getUserList(param);
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
Array length is 0 but if i do a console.log(userList) before the loop , the array display the list of user data
this.getSelectedUserName = function (id, param) {
var name = "";
var userList =this.getUserList(param);
console.log(userList) ;
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
Thank you for kind responses.
Please see screenshot
This is simple Javascript, not specific to Angular. You can do
userList.forEach(user => {
if(user.userId === id) {
name = user.name;
}
});
return name;
you can try like this.
here we are using a async await.
Service
this.getUserList = function (val) {
var usersObj = [];
var url = "/api/v1/hello/getusers";
var params = { Id: val.Id, SettingId: val.SettingId };
var config = { params: params };
return new Promise((resolve, reject) => {
$http.get(url, config)
.then(function (response) {
angular.forEach(response.data, function (key, value) {
angular.forEach(key, function (k, index) {
usersObj[index] = ({ userId: k.userId, name: k.name});
});
});
},
function errorCallback(response) {
console.log("Unable to perform get request");
throw response;
});
var usersList = usersObj;
resolve(usersObj);
});
};
this.getSelectedUserName = async function (id, param) {
var name = "";
var userList = await this.getUserList(param);
console.log(userList);
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
let me know if it is working or not.
EDIT:
If you're only trying to match one id in the array of users you don't even need to loop:
anArray = source.filter(source => source.toLowerCase().indexOf(id) === 0);
or
anObject = source.find(obj => obj.id === id);
Which Angular version is this? Your tag denotes 2.+ but you have $scope there which is ng1.x
Why can't you use ngFor in your view since you already have your arrays. You don't need to sort them in the control.
component
this.getSelectedUserName = function (id, param) {
let name = ""; // should be array if you want to add unames to it
let userList = this.getUserList(param);
// what is `angular` here? And why loop here? Use ngFor in view.
angular.forEach(userList, function (value, key) {
if (value.userId == id){
name = value.name; // will be overwritten each time
// should be name.push(value.name); // but loop in view instead
}
});
// this.users = name; // for your original sorted version
this.users = userList;
}
In your view
<li *ngFor="let user of users; index as i;>
{{user.name}}
</li>

Values are not stored in array AsyncStorage react native

I am trying to store values in AsyncStorage as array, but values are not saving there and getting nothing when i try to get the values from array.Any help would be appreciated.Thank you in advance,here is my code :
let searchString = this.state.inputValue
AsyncStorage.getItem('searches', (res) => {
var searches
if (res === null) {
searches = []
}else {
searches = JSON.parse(res)
}
searches.push({
searchString: searchString
})
AsyncStorage.setItem('searches', JSON.stringify(searches), (res) => {
console.log('====FirstPage====setItem==async==='+res)
})
});
//getting values from asyncstorage :
AsyncStorage.getItem('searches', (res) => {console.log('===res==='+res)})
Please try this
AsyncStorage.getItem("searches").then((value) => {
this.setState({"searches": value});
}).done();
Also see
https://www.thepolyglotdeveloper.com/2015/09/saving-data-in-your-react-native-mobile-application/
You can store the data as following:
AsyncStorage.setItem('searches', JSON.stringify(searchString));
In order to fetch/get, you can do that using following:
AsyncStorage.getItem('searches', (err, result) => { // err indicating the error
console.log("Storage Data(String):", result); // print is string format
console.log("Storage Data(Object):", JSON.parse(result)); // print is json format
})

Add "where" query in Sequalize based on flag

I want to add "where" query in Sequalize based on flag . Let me know how to get this.
For example if the flag is true then I want to add this "where" class otherwise I don't want to add the "where" clause.
models.Users.findAll({
where: {
email: req.query.email
}
}).then(function (list) {
res.send(list);
}).catch(function (error) {
res.status(500).json(error);
});
models.Users.findAll({
}).then(function (list) {
res.send(list);
}).catch(function (error) {
res.status(500).json(error);
});
You can create JSON first which you are providing in where clause and then pass it in where clause.. something like
var jsonObj = null ;
if (req.query.email){
jsonObj = {"email": req.query.email};
} else {
jsonObj = {"email": {$ne:null}}; //otherwise it will return all rows, if email is not null in your database
}
models.Users.findAll({
where: jsonObj
}).then(function (list) {
res.send(list);
}).catch(function (error) {
res.status(500).json(error);
});
Hope this will help
You can start with an empty query object, and add a where property to it when appropriate:
let query = {};
if (someCondition) {
query.where = { email: req.query.email };
}
models.Users.findAll(query).then(...);
You can use simple one-line if statement inside the findAll method call. Let's assume that variable is your boolean flag
models.Users.findAll(variable ? { where: { email: req.query.email } } : {}).then(list => {
res.send(list);
}).catch(error => {
res.status(500).json(error);
});
Or you can assign the options object to a variable and use the same if statement, but outside the findAll call
let options = variable ? { where: { email: req.query.email } } : {};
models.Users.findAll(options).then(list => {
// ...
});

Resources