Array of object - get id for selected user name inside function - javascript

const user = [
{name:"jonh" ,id:EAD1234},
{name:"peter" ,id:EAD1235},
{name:"matt" ,id:EAD1236},
{name:"henry" ,id:EAD1237},
]
I have above mentioned array of object,
I want to get selected user id dynamically based on user selection using es6 and javascript e.g. if i select john i should get EAD1234. and it must suitable on large number of records
I tried using filter method

No need to filter through the whole array if the id values are unique:
function getUserByID(id, users) {
for (const u of users) {
if (u.id === id) {
return u;
}
}
return null;
}
If your data really is exceptionally large and it makes sense to store it on the front-end look into using IndexedDB.
Edit: Someone in the comments somewhere mentioned Array.prototype.find(), so you might as well just use the built-in.
function getUserByID(id, users) {
return users.find((u) => u.id === id) || null;
}

If the data is samll,then just combine Array.filter() and Array.map() can do it.
If the data is too large,we can store the data into a database such as mysql or redis,then query it dynamiclly
const user = [
{name:"jonh" ,id:'EAD1234'},
{name:"peter" ,id:'EAD1235'},
{name:"matt" ,id:'EAD1236'},
{name:"henry" ,id:'EAD1237'}
]
let id = 'EAD1234'
let result = user.filter(u => u.id === id).map(u => u.name)
console.log(result)

const user = [
{name:"john" ,id:'EAD1234'},
{name:"peter" ,id:'EAD1235'},
{name:"matt" ,id:'EAD1236'},
{name:"henry" ,id:'EAD1237'},
];
let userName = "john";
let userId = user.filter(user => user.name === userName)[0].name;

Related

Retrive alle values as array on key in firebase for react native

Hey i have a list of calendar evnets where the key is by date but i would like u get out all values as a array of data
but i wish to get the data out kinda like this but ofc with the rest of the values i have
'2012-05-25': [{date: '2021-04-10', name: "",},{date: '2021-04-10', name: "",}]
is there any way using firebase query to get it out in the format over ?
Something like this should do the trick:
cons ref = firebase.database.ref("calendar/events");
ref.once("value").then((snapshot) => {
let result = {};
snapshot.forEach((daySnapshot) => {
result[daySnapshot.key] = [];
daySnapshot.forEach((eventSnapshot) => {
result[daySnapshot.key].push(eventSnapshot.val());
})
})
console.log(result);
});
So we load all data from the database and then use two nested forEach loops to handle the dynamic levels underneath, and result[daySnapshot.key] to get the date key.

Get cypress database query output objects in to variables

I have a cypress test which has been set up with mysql node module. When I run bellow mentioned test Its giving output as follows.
const executeQuery = (query) => {
cy.task('DBQuery', query).then(function (recordset) {
var rec = recordset
cy.log(rec)
})
}
Query:
select *
from Users
where email = 'sheeranlymited#lymitedtest.com'
OUTPUT: log [Object{23}]
Query:
select firstname
from Users
where email = 'sheeranlymited#lymitedtest.com'
OUTPUT: log [{firstname: Edward}]
instead of cy.log(rec) I want to get the output of 23 columns to assign in to different variables based on the column name.
Appreciate if someone can help me to resolve this...
You can use Object.values in js to retrieve values from your object
Let's say you need to extract the value of the 3rd column, so your code will look like,
cy.task('DBQuery', query).then(function (recordset) {
var rec = recordset
const results = Object.values(rec[0])
// results[index of the column] will output the results
cy.log(results[3])
})
We can do a small modification to make your task easier,
cy.task('DBQuery', query).then(function (recordset) {
var rec = recordset
const Values = Object.values(rec[0]);
const keys = Object.keys(rec[0]);
let result = {};
let index = 0;
keys.forEach(key => {
result[keys[index]] = Values[index];
i++
})
//result.firstName will give you your results
cy.log(result.firstName);
})
In this way, we are generating key-value pairs having the key as the column name. So you can use the column name to find the value.
Hope this helps.
cheers.

How to loop through the data I receive from snapshot.val() and push it to an array based on keys

I want to loop through the data I receive from snapshot.val() based on user keys and push them into an array. I tried doing it with the help of for..in loop like this,
firebase.database().ref('\interests').child("I would like to dine with").on('value', (snapshot) => {
var data = snapshot.val();
if(snapshot.exists()){
for(let key in data){
console.log("data[key]",data[key]);
this.intVal.push(data[key]);
console.log("intVal",this.intVal);
}
}
})
But I'm getting something like this,
If you notice, my first array contains 1 object under a user key and my second array contains 3 objects under their user keys. How can I push every single value in a separate array?
Any help would be much appreciated! Thanks
There is a DataSnapshot.forEach() method precisely for this purpose:
firebase.database().ref('\interests').child("I would like to dine with").on('value', (snapshot) => {
snapshot.forEach((child) => {
console.log(child.key, child.val());
this.intVal.push(child.val());
console.log("intVal",this.intVal);
});
}
})
You can iterate over data again for each object
for(let key in data){
console.log("data[key]",data[key]);
for(innerKey in data[key]){
var obj = {};
obj[innerKey]=data[key][innerKey];
this.intVal.push(obj);
}
console.log("intVal",this.intVal);
}
Have not tested this code yet but should fit your need.
var interest = data.pop();//remove the interest
var uniq = data.reduce((unique, users) => {
for (userId in users) {
if (!userId in unique.IDs) {
unique.IDs[userId] = users[userId];
unique.usersList.push(users[userId]);
}
}
return unique;
}, {IDs:{},usersList :[]});
console.log('interest is', interest);
console.log('uniq user ids', Object.keys(uniq.IDs));
console.log('uniq user list', uniq.usersList);
Just using array map can solve all pain i think.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

How to add/replace inner object inside JavaScript array

I have a JavaScript array with the form of
const Rooms = [{
name:"Science",
students:[
{user:"Tom",emotion:"Happy"},
{user:"Marry",emotion:"Angry"},
{user:"Adam",emotion:"Happy"}]
},{
name:"Maths",
students:[
{user:"Stewie",emotion:"Angry"},
{user:"Cleavland",emotion:"Angry"},
{user:"Meg",emotion:"Happy"},
{user:"Peter",emotion:"Angry"},
{user:"Chris",emotion:"Happy"}]
},{
name:"History",
students:[
{user:"Monica",emotion:"Angry"},
{user:"Chandler",emotion:"Happy"},
{user:"Joe",emotion:"Happy"},
{user:"Ross",emotion:"Angry"}]
}];
I need to find a room by name and add/replace it by student when needed. It means I should be able to find the Room (Maths) and add/update student. If student is already there then its emotion should be changed.
This is the code that I tried but it didn't replace the existing student.
Rooms.forEach((e)=>{if(e.name === "Science"){
e.students.push({user:"Tom",emotion:"Surprised"});
}});
How can I search for a particular json and change the existing student or add a new student data (if student is not present)?
Use find in the array of the students:
For instance, to finding "Tom" and updating it:
Rooms.forEach((e)=>{
if(e.name === "Science"){
const tom = e.students.find((student) => student.user === "Tom");
if (!tom)
e.students.push({user:"Tom",emotion:"Surprised"});
else
tom.emotion = "Surprised";
}
});
Note: you may also be using find for finding the room instead of using forEach:
const e = Rooms.find((room) => room.name === "Science");
if (e) {
const tom = e.students.find((student) => student.user === "Tom");
if (!tom)
e.students.push({user:"Tom",emotion:"Surprised"});
else
tom.emotion = "Surprised";
}
}

How to get result from json object with angular js?

I have a json file and want to count the rows by specific value and load to my page using angular js models.
The json is look like this:
[
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
]
The json file loaded by $http service.
How can I run such query on the json data:
select COUNT(`name`) as a from tbl_ben where ` gender` = 'Female' and `district` = 'LA';
any idea? 
 
You can't run SQL queries on JSON out-of-the-box, so let's work through it in JavaScript.
We have some data in an array, let's call it people:
let people = [
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
];
Now, let's filter it down based on their gender and district like in your query:
let filtered = people.filter(p => (p.district === "LA") && (p.gender === "Female"));
Now instead of using COUNT, we can just check the length property of our filtered array:
let count = filtered.length;
We can abstract this code away into a nice function which will do the work for us:
let getCount = (array, predicate) => {
return array.filter(predicate).length;
};
And we can then use this function like so:
let people = [
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
];
getCount(people, p => p.district === "NY" && p.gender === "Male"); // 1
Note that based on your example data, the count is 0 as you have nobody in the district "LA".

Categories

Resources