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);
Related
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;
}
}
I'm trying to add a validation chain on an object which contain an array;
this array contain objects that have to be tested differently according to one of the field of the object,
here is an example :
{
"title" : "my title",
"sections" : [
{
"type": "A",
"optionsA" : {...}
},
{
"type": "B",
"optionsB" : {...}
},
{
"type": "A",
"optionsA" : {...}
},
{
"type": "C",
"optionsC" : {...}
},
]
}
is there a way to achieve this ? i tried to use OneOf() with specific test for each section but with no success
while this solution is a bit more work I think it's the most straightforward and maintainable.
Download the Validator & Is-emptypackages
Using this package you can validate and JSON object with a lot of control. So I use it like this to validate my req.body
const Validator = require('validator');
const isEmpty = require('is-empty');
module.exports = function validateRegiterInput(data) {
let errors = {};
//Convert empty fields to a empty string so we can use validator functions
data.firstName = !isEmpty(data.firstName) ? data.firstName : "";
data.lastName = !isEmpty(data.lastName) ? data.lastName : "";
data.email = !isEmpty(data.email) ? data.email : "";
data.password = !isEmpty(data.password) ? data.password : "";
//school, schoolname? tbd
//Name check
if (Validator.isEmpty(data.firstName)) {
errors.firstName = "First name is required!"
}
if (Validator.isEmpty(data.lastName)) {
errors.lastName = "Last name is required!"
}
//Email check
if (Validator.isEmpty(data.email)) {
errors.email = "Email field is required!";
} else if (!Validator.isEmail(data.email)) {
errors.email = "Email is invalid!";
}
//Password check
if (Validator.isEmpty(data.password)) {
errors.password = "Password field is required!";
}
if (!Validator.isLength(data.password, { min: 6, max: 30 })) {
errors.password = "Password must be at least 6 characters!";
}
return {
errors,
isValid: isEmpty(errors)
};
};
So what happens is, I call this function with my data and im able to nest into arrays or objects just using the dot notation.
In the main file, I have this
const { errors, isValid } = validateRegisterInput(req.body);
If there were any errors then they'll be in the errors object. and is valid will be false. Otherwise, if it's empty the is valid is true and you're good to go. I hope this helped. If you need more clarification I'm here to help
How can I extract the 'jobs' object from a nested json list like this:
result:
{
person:
[
{
name: ""
address: ""
jobs: [
{
company:""
},
{
company:""
}
]
}
]
}
Thank you
Write a generic method to extract object properties.
function onExtract(key, data) {
if (isObject(data)) {
for (let item in data) {
if (key === item) {
return data[item];
}
const res = onExtract(key, data[item]);
if (res !== null) return res;
}
}
if (isArray(data)) {
for (let item of data) {
const res = onExtract(key, item);
if (res !== null) return res;
}
}
return null;
}
function isObject(obj) {
return Object.prototype.toString.call(obj) === "[object Object]";
}
function isArray(arr) {
return Object.prototype.toString.call(arr) === "[object Array]";
}
// test
const data = {
person: [
{
name: "",
address: "",
jobs: [
{
company: ""
},
{
company: ""
}
]
}
]
};
console.log(onExtract("jobs", data));
let's say you have a return var that contains this json value
let mappedCompanies = return.person.map(person =>
person.jobs.map(job => job.company)
).flatMap(m => m)
mappedCompanies would contain an array with all the companies names for each one of the registers in "person", all as one array of strings
you can read more about Array.map() here: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/map
A dynamic way to query the person[] and find jobs, is to use the javascript map() method.
Here is the code without comments.
const personsJobs = (personName, personAddress) => {
const jobs = result.person.map((el) => {
if (el.name === personName && el.address === personAddress) {
return el.jobs;
} else {
return null;
}
})
.filter((el) => el !== null);
return jobs;
};
console.log(personsJobs("wyatt", "1234 test ln"));
Here is the code with comments to explain how the personsJob function works.
// Blow is an ES6 arrow function with the parameters 'personName' and 'personAddress',
// which represents the person in which you are querying for jobs (using both a persons
// name and address so in the case of persons with the same name, you only find the jobs
// of the person you want).
const personsJobs = (personName, personAddress) => {
// Since 'person' is an array, we can use the 'map' method as stated before, which
// will create a new array (jobs) that will store the jobs a specific person has.
const jobs = result.person.map((el) => {
// el stands for the current position in the person array.
// if el's (the current person) name and address values are equal to that of the
// parameters personName and personAddress, then that persons jobs are added to the jobs // array, however, if el does not satisfy the two parameters, null is added to the jobs
// array.
// The array, upon completion, will look something like this: ["programmer", null, null]
if (el.name === personName && el.address === personAddress) {
return el.jobs;
} else {
return null;
}
})
// Finally, the filter method is called to remove all null values so that you will
// only have the persons job in the jobs array.
// After filtering, the array will look like this: ["programmer"]
.filter((el) => el !== null);
return jobs;
};
// Prints the array of wyatt's jobs
console.log(personsJobs("wyatt", "1234 test ln"));
So, following the conclusion of the function, you will have dynamically found the jobs of a specific person.
you can use flatMap function like:
const jobsData = result.person.flatMap(item => item.jobs);
Here is a flexible solution using object-scan
// const objectScan = require('object-scan');
const data = { person: [{ name: '', address: '', jobs: [{ company: '' }, { company: '' }] }] };
console.log(objectScan(['person[*].jobs'], { reverse: false, rtn: 'value' })(data));
// => [ [ { company: '' }, { company: '' } ] ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#14.0.0"></script>
Disclaimer: I'm the author of object-scan
I have to check if some items object follow a certain format as below. These items are input to a component and I want to check the validity of the input.
I already wrote some code to check for the validity of the items, but I want to know if there could be a better way to write it?
Thanks!
{
main: {
id: string,
name: string,
},
drilldowns: [
{
id: string,
name: string,
elements: [
{
id: string,
name: string,
}
],
}
],
}
export const isValidItem = (item) => {
if (!item.main || (item.main && !item.main.id))
return false;
if (item.drilldowns) {
const invalidDrilldowns = item.drilldowns.filter(drilldown => {
const invalidDrilldownElements =
drilldown.elements &&
drilldown.elements.filter(element => {
return !element.id;
});
return (
!drilldown.id &&
!drilldown.elements &&
invalidDrilldownElements.length !== 0
);
});
return invalidDrilldowns.length === 0;
}
return true;
};
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'));