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:
Related
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.
SO I have array1 with values ["folderid":"DTSZ", "folderid":"IEACF6FVGG", "folderid":"IEACKQC6A"] and another array 2 with values ["title":"firsttitle", "title":"second","title":"thirdtitle"]
Now lets say using javascript i want to save it as json object.
[
{"folderid":"DTSZ","title":"firsttitle"},
{"folderid":"IEACF6FVGG", "title":"second"},
{"folderid":"IEACKQC6A", "title":"thirdtitle"}
]
I trying looping and concat but didn't work properly.
array1= ["folderid":"DTSZ", "folderid":"IEACF6FVGG", "folderid":"IEACKQC6A"] ;
array2 = ["title":"firsttitle", "title":"second","title":"thirdtitle"];
Get array with json objects
[
{"folderid":"DTSZ","title":"firsttitle"},
{"folderid":"IEACF6FVGG", "title":"second"},
{"folderid":"IEACKQC6A", "title":"thirdtitle"}
]
In JavaScript an array has just values, in you examples the array is invalid since you try to add direct key: values elements . i.e.
["folderid":"DTSZ"] // invalid !! (notice semicolon)
["folderid", "DTSZ"] // VALID (notice comma)
If you want to translate to a valid array and then to an object, you could use something like entries, which are array of arrays.
Let's take your first example and convert it to entries:
const arr1 = [["folderid", "DTSZ"], ["folderid", "IEACF6FVGG"], ["folderid","IEACKQC6A"]]
Then to convert this to object you can use Object.fromEntries just like this:
const obj1 = Object.fromEntries(entries);
So, focus first to convert your initial invalid arrays to entries, and then the job is done!
use the following code.
var a = [{ "folderid": "DTSZ" }, { "folderid": "IEACF6FVGG" }, { "folderid": "IEACKQC6A" }]
var b = [{ "title": "firsttitle" }, { "title": "second" }, { "title": "thirdtitle" }]
var newObject = a.map((o, index) => {
const temp = Object.assign(o, b[index]);
return temp;
});
console.log('output ---- ', newObject)
I am querying my db in node and have got the result in the form of an object like this - [ [1234] ].
I want to extract this value and convert it into a string and then pass it onto the client side. I have written the other required code but I am not able to get value from this object. Can anyone help me in getting the value and converting it to string?
Since, the result you've got is a two-dimensional array, you can get the value and convert it into a string (using toString() method) in the following way ...
var result = [ [1234] ];
var string;
result.forEach(function(e) {
string = e.toString();
});
console.log(string);
** this solution will also work if you have multiple results, ie. [ [1234], [5678] ]
You have a nested array, meaning that you have an array inside another array:
[ [1234] ]
// ^-^====^-^
To get the first value of the parent array, use the square brackets: [0]. Remember that indexes start at 0!
If you have val = [[1234]], val[0] gets the enclosed array: [1234]. Then, 1234 is a value in that array (the first value), so you use the square brackets again to get it: val[0][0].
To convert to string, you can use + "" which forces the number to become a string, or the toString() method.
var val = [[1234]];
var str = val[0][0] + "";
// or val[0][0].toString();
console.log(str, typeof str);
You can read more about arrays here.
var response = [ [1234] ];
console.log(response[0][0]);
to extract values from a string array or an array we can use .toString()
Ex:
let names = ["peter","joe","harry"];
let fname = names.toString();
output = peter ,joe,harry
or
let name:string[] = this.customerContacts.map(
res => res.firstname
let fname =name.toString();
Using De-structuring Array concept:
const arr = [[1, 2, 3, 4, 5]];
const [[p, q, r, s, t]] = arr;
console.log(p, q, r, s, t);
Output: 1 2 3 4 5
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()
I am fetching data from a text file and need help in making the information into an object..
Array:
['celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n' ]
I need the values till \n in one object
expected result:
[{'celestine,timmy,celestinetimmy93#gmail.com,repeat 124}
{arun,mohan,reach#gmail.com,repeat 124213}
{jalal,muhammed,jallu#gmail.com,rave1231212321}
{vineeth,mohan,get,rave1231212321} ]
you can do in this way.
after applying splitting by '\n'
['celestine,timmy,celestinetimmy93#gmail.com,repeat
124\narun,mohan,reach#gmail.com,repeat
124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n'
]
you will get single one dimensional array.
["celestine,timmy,celestinetimmy93#gmail.com,repeat 124", "arun,mohan,reach#gmail.com,repeat 124213", "jobi,mec,mec#gmail.com,rave", "jalal,muhammed,jallu#gmail.com,rave1231212321", "vineeth,mohan,get,rave1231212321", ""]
Then looping it to get each individual record.
JS :
var test = ['celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n' ]
var arrString = [];
test.forEach(function(val,key){
arrString = val.split('\n')
});
console.log(arrString);
arrString.forEach(function(val,key){
console.log(val.split(','));
})
In order to create an object, you'll need to format the string inside the curly braces as a dictionary of key value pairs. I am not sure what the keys or values are in your case. However if I assume that the key is "key" and the value is the text then:
var txt = 'celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n';
// Use trim, to remove the trailing whitespace, in your case a '\n'
// Use split to convert the text into an array of elements
var arr = txt.trim().split('\n');
// Use the map function to map each string to an object
var objects = arr.map(function(element) {
return { key: element};
});
Here is the output:
objects = [ { key: 'celestine,timmy,celestinetimmy93#gmail.com,repeat 124' },
{ key: 'arun,mohan,reach#gmail.com,repeat 124213' },
{ key: 'jobi,mec,mec#gmail.com,rave' },
{ key: 'jalal,muhammed,jallu#gmail.com,rave1231212321' },
{ key: 'vineeth,mohan,get,rave1231212321' } ]
try this idea.
var x = "celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n";
var y = x.split("\n");
implement the remaining part. convert the array of arrays into array of objects using loops