JOI :allow null values in array - javascript

I am trying to add a validation for array in a POST request
Joi.array().items(Joi.string()).single().optional()
I need to allow null values in the payload. Can you please tell me how this can be done ?

If you want to allow the array to be null use:
Joi.array().items(Joi.string()).allow(null);
If you want to allow null or whitespace strings inside the array use:
Joi.array().items(Joi.string().allow(null).allow(''));
Example:
const Joi = require('joi');
var schema = Joi.array().items(Joi.string()).allow(null);
var arr = null;
var result = Joi.validate(arr, schema);
console.log(result); // {error: null}
arr = ['1', '2'];
result = Joi.validate(arr, schema);
console.log(result); // {error: null}
var insideSchema = Joi.array().items(Joi.string().allow(null).allow(''));
var insideResult = Joi.validate(['1', null, '2'], insideSchema);
console.log(insideResult);

the very short answer is:
name: Joi.string().allow(null)

I know what i'm posting is not what you are looking for,
but as i was ran into similar type of problem.
so my problem was: I do not want to allow empty array in my object
my solution:
// if you have array of numbers
key: joi.array().items(joi.number().required()).strict().required()
// if you have array of strings
key: joi.array().items(joi.string().required()).strict().required()

Related

Combine 2 Array into a new string

I have 2 Javascripts Array
var array1 = ["Mergen Morry","Dash Borad","Mergen Xss"];
var array2 = ["02111356","4458763","02111356"];
I want the output to be like this
Mergen Morry – 02111356 : data uploaded
Dash Borad - 4458763 : data uploaded
Mergen Xss – 02111356 : id already registered
I was thinking using join(), but as I recall this is 2 array, and using concat() are out of question, and maybe was thinking using map() or forEach(), but I still don't get how.
Edit : I'm sorry, the output should be string not array.
You could take an object for keeping seen id and return appropriate comments for mapping strings.
const
names = ["Mergen Morry", "Dash Borad", "Mergen Xss"],
ids = ["02111356", "4458763", "02111356"],
result = names.map(
(seen => (s, i) => `${s} - ${ids[i]} : ${ seen[ids[i]]
? 'id already registered'
: (seen[ids[i]] = true, 'data uploaded') }`)
({})
).join('\n');
console.log(result);
#Nina Scholz answer is pretty good, and here the another way you could have json with all its content instead.
var array1 = ["Mergen Morry","Dash Borad","Mergen Xss"];
var array2 = ["02111356","4458763","02111356"];
var res = array1.map((item,index)=>{
return {name:item,id:array2[index]}
},[]);
// Now that you have an array with Id and namne, you could loop throw each array and display the data
console.log(res)

Vue.js computed properties, filter by object key

I'm working with an object containing multiple network interfaces with the interfaces' names as keys and then interfaces' informations as values :
What I would like to do is a Vue.js computed property to filter this object by Keys and create arrays that contain all GigabitEthernet separately for example so I can iterate over it in my template.
I thinked about using Regex, here is the one that I use and match the interfaces I want to put in a separate array :
const regex = /^(Te|GigabitEthernet|FastEthernet)+\s?([0-9]+\/){0,}[0-9]+$/g;
The problem is that the main object received from API isn't an array so I can't use find() or filter() functions over it...
If anyone as any idea it would be nice, thanks !
EDIT :
After trying Jaromanda's solution :
It returns only 1 line out of 2...
Here is the code :
const regex = /^(Ten|GigabitEthernet|FastEthernet)\d+[/]?[\d+]?[/]?[\d+]?[.]?[\d+]?[/]?[\d+]?[/]?[\d+]?[:]?[\d+]?$/g;
var rslt = {};
Object.fromEntries(
Object.entries(this.cmdResult).filter(([key, value]) => {
if (regex.test(key)) {
rslt[key] = value;
}
})
);
return rslt;
Here is a screenshot of current output at the left and expected output at the right :
EDIT 2 :
Here is what happens when I console log the regex results with the associated key :
As you can see only 1 out of 2 is true...
This is other solution, using map.
const cmdResult = {
"GigabitEthernet1/0/2": {name: ""},
"GigabitEthernet1/0/3": {name: ""},
"GigabitEthernet1/0/4": {name: ""}
}
const regex = /(GigabitEthernet||FastEthernet\d+(\.\d)*)/i;
const rslt = {};
Object.keys(cmdResult)
.filter((key) => regex.test(key))
.map(prop => rslt[prop] = cmdResult[prop])
console.log(rslt);

How to compare if two arrays have duplicate values and return the different value?

I have two arrays and I would like to compare if these arrays have duplicated values, then return the values that aren't duplicates. Based on these two arrays I would like to return the string Eucalipto.
const plants = [
{
id: 59,
kind: "Cana-de-açucar"
},
{
id: 60,
kind: "Citros"
}
];
const auxPlants = [
"Cana-de-açucar",
"Citros",
"Eucalipto"
]
You can use Array#map to find all the kind values, pass that to the Set constructor, and then use Array#filter to find all elements of the array not in that Set.
const plants = [
{
id: 59,
kind: "Cana-de-açucar"
},
{
id: 60,
kind: "Citros"
}
];
const auxPlants = [
"Cana-de-açucar",
"Citros",
"Eucalipto"
];
const set = new Set(plants.map(({kind})=>kind));
const res = auxPlants.filter(x => !set.has(x));
console.log(res);
sounds like you want to filter the array of values you're interested in based on if they're not found in the other array, like so:
const nonDuplicates = auxPlants.filter(a => !plants.find(p => p.kind === a))
it's unclear if you'd also want values from the plants array that are non duplicate as well, or if you're only interested in uniques from the auxPlants array
This is the solution to it, I have explained it's working using comments
// create a set in order to store values in it
// assuming you have unique values
let set = new Set();
// iterating over array of object and storing the value of 'kind' in the set
for(obj of plants){
set.add(obj.kind);
}
// iterating over array and checking for values in set,
// if not in set then printing it
for(ele of auxPlants){
if(!set.has(ele)){
console.log(ele);
}
}
As said, please search for an already posted solution first. Here's what I found.
Anyhow, the solution would be to separate the types of plants from the first array, as so:
const plantsTypes = plants.map(obj => obj.kind)
Then, filter out the non duplicates:
const nonDuplicates = auxPlants.filter(plant => !plantsTypes.includes(plant))
Note that it matters which array you call the .filter() function on.

JS Array in JSON by Mongoose Schema

The problem that I cant get access to array in array. Here is my Mongoose Schema:
const newSchema = mongoose.Schema({
email : String,
name : String,
array : [Number]
})
And here is data, which I put in array:
{
"array": [
-11,
"10,10,0",
"1"
]
}
Now I am trying to update the value "10" in the second row like this:
newAccount.array[3,0] = parseInt(someVariable)
or like this
newAccount.array[3][0] = parseInt(someVariable)
But the value doesn't changing in any case. How can I change it correctly?
This is a quick and dirty solution for your problem:
var obj = {
array: [
-11,
'10,0,0',
12
]
}
// splitting by ',' char
const newArray = obj.array[1].split(',')
// enter your new variable here.
newArray[0] = parseInt(someVariable);
// join them together so that we have the old structure back.
obj.array[1] = newArray.join(',');
console.log(obj);
a better approach would be to restructure your data enrichment in that way, that you don't have mixed types in there.
and the outcome:

Remove last letter from map value

So I'm getting this from backend:
{"Item":{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}}
I use Object.Keys to narrow down the contents to:
Drake,Ola,b,d
Which I then map to give:
[{"id":"Drake"},{"id":"Ola"},{"id":"b"},{"id":"d"}]
Which is then used on my Angular Front-end as .id. I want to remove the last letter from each value i.e leaving Drak,Ol etc. I've tried many ways but have failed, how can I achieve this please so that the id has those values?
EDIT
I also want to now get that value that was cut AND add it such that the end product will be [{"id":"Drak",valueThatWasCut:"e"}]
You could iterate the object's keys and build with the short string a new object.
var data = {"Item":{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}},
ids = Object.keys(data.Item.Buddy.contents).reduce(function (r, k) {
var n = k.slice(0, -1);
return n ? r.concat({ id: n }) : r;
}, []);
console.log(ids);
Perhaps something like :
var arr = [{"id":"Drake"},{"id":"Ola"},{"id":"b"},{"id":"d"}];
var result = arr.map(x => x.id.slice(0,-1));
console.log(result); // [ 'Drak', 'Ol', '', '' ]
Create a temporary contents object and change in that.
Then just set this in the original object. ES6 spread operators would save the rest of data without respecifying all keys and values.
let items = {"Item:{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}};
let contents = items.Item.Buddy.contents;
let contentsNew = Object.keys(contents).map((content) => {
return {[content.substring(0, content.length-1)]: content.substring(0, content.length-1), valueThatWasCut: content[content.length-1]};
});
items = {...items, Item: {...items.Item,Buddy:{...items.Item.Buddy,contents: contentsNew}}};
console.log(items);

Categories