Map function in JSON array - javascript

I want to find an object from a JSON array. My code is working fine with the object found. But the issue is what if the employee id is not? My code console's "not found" two times. Kindly guide me on what the issue is with my code.
var E_ID
let empArray = [
{
"employee": {
"employee_ID": 16,
"employee_designation": "Node.js",
"employee_FirstName": "John",
"employee_lastName": "Doe",
}
},
{
"employee": {
"employee_ID": 17,
"employee_designation": "Full Stack",
"employee_FirstName": "Samual",
"employee_lastName": "Smith",
},
}
]
function search_EmployeeByID(E_ID) {
empArray.map(item => {
if (item.employee.employee_ID == E_ID) {
console.log(item.employee)
return true
}else {
console.log("not found")
return false
}
})
}
E_ID = parseInt(prompt("Enter Employee_ID to search for:"))
search_EmployeeByID(E_ID);`

The if statement should not be inside find(). find() will return the matching element, or null if it's not found. So test the return value.
function searchEmployeeByID(e_id) {
let emp = empArray.find(e => e.employee.employee_ID == e_id);
if (emp) (
console.log(emp.employee);
return true;
} else {
console.log("not found");
return false;
}
}

Related

Validate json with given keys in Javascript and Reactjs

I have below JSON ,
[
{
"name":"john",
"school":"school 2",
"address":"newyork"
},
{
"name":"peter",
"school":"school 1",
"address":"washington"
}
]
here i want to validate below mentioned things,
1 - it should be an array
2 - it must have only 3 fields (name,school,address) not more that or less than these three fields
3 - "school" can be either 'school1' or 'school2' and "address" can be either "newyork" or "washington"
I amneed to do this using react js and javascript
Thanks in advance
Validation using yup
const schema = yup.array()
.of(
yup.object().shape({
name: yup.string().required("Required"),
school: yup.mixed().oneOf(['school 1','school 2']),
address: yup.mixed().oneOf(['newyork','washington'])
}).noUnknown(true)
)
and validate,
await schema.validate(your_object).catch(function (err) {
err.name; // => 'ValidationError'
err.errors;
});
Note: this validation is not tested
Here is a simplified function of what you are trying to do
const validateJSON = (json) => {
if (!Array.isArray(json)) {
return false;
}
for (const element of json) {
if (Object.keys(element).length !== 3) {
return false;
}
if (element.school !== "school 1" && element.school !== "school 2") {
return false;
}
if (element.address !== "newyork" && element.address !== "washington") {
return false;
}
}
return true;
};
then just use const isValid = validateJSON(json);

How to print an array inside object that is coming from database?

I am trying to print an array "data" inside an object "clientData" but the problem is I cant access the array inside before it loads from the database, it gives me an error "Property 'data' does not exist on type '{}'". How do I extract that array without specifying?
this.adnService.getClient().subscribe((result) => {
if (result === null) {
this.empty = true;
}
this.clientData = result;
console.log(this.clientData);
console.log(this.clientData.data[0].client_id);
})
Below is the clientData stringify output
{
"status": "pass",
"data": [
{
"client_id": "u616672",
"client_name": "Client 123"
}
]
}
this.adnService.getClient().subscribe((result) => {
if(result && result != ""){
this.clientData = result;
console.log(this.clientData);
console.log(this.clientData.data[0].client_id);
}else{
this.empty = true;
}
})
(or)
console.log(this.clientData?.data[0].client_id);

How to reference the key from json with node.js

How would I access the following json data
"users":{
"2211392761":{"username":"user1"},
"14300995184":{"username":"user2"},
"2781554712":{"username":"user3"},
"3554341":{"username":"user4"},
"202611":{"username":"user5"},
"17754300653761":{"username":"user6"}
}
I have this so far and I am aware it is completely wrong:
Object.keys(jsonevents["events"]).forEach(function(key) {
if(eventName == jsonevents["events"][key]["name"]){
if(jsonevents["events"][key]["users"]){
if(jsonevents['events'][key]["users"][message.author.id]){
delete jsonevents['events'][key]["users"][message.author.id];
fs.writeFile(eventsjson, JSON.stringify(jsonevents),'utf8');
sayMessage += "```User is no longer part of the event "+jsonevents['events'][key]["name"]+"```";
} else {
sayMessage += "```user is not in the event "+jsonevents['events'][key]["name"]+"```";
}
} else {
sayMessage += "```Why do we have no users```";
}
} else {
//sayMessage += "```No event found```";
}
});
I need to be able to access the key by passing in the username, so user2 would give me 14300995184 so i can then use this to remove the user from the event.
You can search through the Object.entries with find() and return the right object. It will return an array of key/value the key will be what you're after:
let users = {
"2211392761":{"username":"user1"},
"14300995184":{"username":"user2"},
"2781554712":{"username":"user3"},
"3554341":{"username":"user4"},
"202611":{"username":"user5"},
"17754300653761":{"username":"user6"}
}
let found = Object.entries(users).find(([key, value]) => value.username === "user2")
console.log(found && found[0]) // found is undefined if not found
You can iterate over the entries (key-value pairs) of the users object, and use .find to find the username that matches the one you're trying to find. The first item in the entry (the key) will be what you're looking for:
const obj = {
"users": {
"2211392761": {
"username": "user1"
},
"14300995184": {
"username": "user2"
},
"2781554712": {
"username": "user3"
},
"3554341": {
"username": "user4"
},
"202611": {
"username": "user5"
},
"17754300653761": {
"username": "user6"
}
}
}
const findEntry = usernameToFind => {
const foundEntry = Object.entries(obj.users)
.find(([, { username }]) => username === usernameToFind);
if (foundEntry) return foundEntry[0];
};
console.log(findEntry('user5'));
console.log(findEntry('userthatdoesntexist'));

How to verify the particular value of the DB node of firebase database

I have a JSON structure as
{
"engagedUsers": {
"qwe": {
"agent_availability": true,
"conv_id": "parthengineer_qwe",
"emailId": "qwe#gmail.com",
"login_time": 1512644440,
"name": "qwe",
"uid": "adasfklsfjdskldgsgjgjkl"
},
"tt": {
"agent_availability": true,
"conv_id": "genesis_tt",
"emailId": "tt#gmail.com",
"login_time": 1512644440,
"name": "tt",
"uid": "adasfklsfjdskldgsgjgjkl"
}
}
}
I want to verify if the conv_id child is equal to parthengineer_qwe. I tried the below code but cannot got through it:
this.engagedRef = firebase.database().ref('engagedUsers');
this.engagedRef.orderByValue().once('value', function (snapshot) {
snapshot.forEach(function (data) {
// console.log("snapShot:" + data.child('conv_id').val());
if ((data.child('conv_id').val() == 'parthengineerqwe') && (existEngageduser !== 1)) {
existEngageduser = 1
// console.log("under haschild:" + existEngageduser);
}
if (existEngageduser == 1) {
isEngaged = true
// sessionStorage.isEngaged = isEngaged;
}
// console.log("isEngaged:" + isEngaged);
})
return isEngaged;
});
Please suggest a better way to achieve this as I know I am not going right way, I expect isEngaged variable as true
I'm still not sure what you want but why not have an external function to do it?
snapshot.forEach(function (data) {
if (isEngaged(data.val())) {
console.log(data.key, ' is engaged');
}
}
function isEngaged(userData) {
return (userData.conv_id === 'parthengineer_qwe') || false;
}

Advanced Array.prototype.filter with Javascript

I have an Javascript object like so...
var strategies = [{
"strategy": {
"category": "war"
}
}, {
"strategy": {
"category": "farming"
}
}]
I then have an array that indicates which results I'd like back. It can be any of the following: [] OR ["war"] ["farming"] OR ["war", "farming"].
If we have the [], I want to return no results. But if ["war", "farming"] I want to return both of the results above.
How do I accomplish this with Array.prototype.filter? I saw this post, but couldn't reason through it.
strategies.filter((strategy) =>
????
)
Thanks for your help.
You can just check the value with indexOf:
var categories = ['war', 'farming'];
var filtered = strategies.filter((obj) => {
return categories.indexOf(obj.strategy.category) > -1;
});
Your object, strategy was a wrapped object, so my first line was setting it to its inner strategy and then filter as needed.
var strategies = [{
"strategy": {
"category": "war"
}
}, {
"strategy": {
"category": "farming"
}
}]
var b = ["war", "farming"];
strategies.filter(function(strategy){
strategy = strategy.strategy;
for(var i in b){
if (b[i] == strategy["category"]) {
return true;
}
}
return false;
});
Tests the input array to see if it's empty as per your requirements:
function filterObj(arr) {
return !arr.length ? arr :
strategies.filter((el) => arr.indexOf(el.strategy.category) > -1);
}
filterObj(['war', 'farming'])
DEMO

Categories

Resources