im using lodash, and im trying to convert a array of numbers in strings, but only convert the numbers since in my array there are null values. I tried using map of lodash in than map from javascript but is messing up the null values.
Example of array:
[1245, 5845, 4585, null, null]
code:
var meds = _.map(lines,'med_id').map(String);
Result: ["1245", "5845", "4585", "null", "null"];
Should be: ["1245", "5845", "4585", null, null];
You need to test the type of the value before calling String
var meds = _.map(lines, 'med_id').map(function(x) {
return typeof x == 'number' ? String(x) : x;
});
That's because String will convert anything it takes into a string. You need to make a custom function that only generates a string if the value isn't null.
_.map(lines, 'med_id').map(function(x) {
if (x !== null) {
x = x.toString();
}
return x;
});
In looking at: https://lodash.com/docs#map
it looks like:
function toInts(n){
if(isNaN(n)){
return null;
}else{
return n;
}
}
_.map(lines,'med_id').map(lines,toInts);
would do the trick.
(Not Tested)
Related
I need to convert JSON object to a string. However, for NULL value in the string, I must change it to an empty string. For it, I overwrite the replacer function
var str = JSON.stringify(rec, function (k, v) { return (v !== null) ? v : ''; });
It works fine. However, it will also change all non-string type value to an empty string. For example, I have the following object
Order Record
------------
OrderId [int] NOT NULL,
ProductId [int] NOT NULL
...
...
...
ReferralMemberId [int] NULL,
Notes [nvarchar](64) NULL
If I use the function above, when ReferralMemberId is NULL, the field will become empty string. Ideally, I would like ReferralMemberId to keep to be NULL, but Notes to become empty string.
Any idea?
Thanks
In JSON, values must be one of the following data types:
a string
a number
an object (JSON object)
an array
a boolean
null
So, typeof value == 'string' doesn't work here, as null is also a data type.
We can solve this by using an extra hashmap.
Declare a HashMap.
Store your data Fields name as key and their data type as value.
Then check during JSON conversion as the data type is a string or not.
let map = new Map();
map.set('OrderId','int');
map.set('ProductId','int');
map.set('ReferralMemberId','int');
map.set('Notes','string');
...
...
function (key, value) {
if (map.get(key) === 'string'){
if(value !== null){
return value;
}else{
return '';
}
}else{
return value;
}
});
trying to check for an empty string or an element that is not a number when run a Number() over it
const latLong = ['1', 'g']
function findError(obj) {
// console.log(Number(obj))
return obj === '' || Number(obj) === NaN
}
console.log(latLong.find(findError))
It seems to be catching the empty string but not the Number() part, any help will be appreciated
For checking Nan, you can use the inbuilt isNaN() function. Check the documentation here
.
let latLong = ['1', 'g'];
latLong = latLong.filter(el => {
return el === '' || isNaN(el);
});
isNaN() is a method in javascript which is used to determine whether a particular value is a number or not.
Above code returns if any element in the array is empty or Not a Number.
I had a node.js app where it takes JSON object and then it encrypts the JSON object key value. I had a function which takes value and then encrypts data. Now I need to iterate only the JSON key value to the function which I'm able to do using.
var JsonData = JSON.parse(jsonString);
var callFunction = iterate(JsonData);
function iterate(JsonData) {
for (var exKey in JsonData) {
if (JsonData.hasOwnProperty(exKey)) {
if (typeof JsonData[exKey] == "object") {
iterate(JsonData[exKey]);
} else {
JsonData[exKey] = encrypt(JsonData[exKey]);
}
}
}
}
var encrpted = JSON.stringify(JsonData);
But the problem is I'm able to iterate only the string type JSON object.i.e., (ex {"name":"sam","gender":"male"}). If we are having JSON object with boolean or number or both type along with string type,it is not able to iterate and I'm getting some error..(ex. {"name":"sam","age":21,"isMarried":false}).
So how can I iterate through that function if I have other than string type? I know that using replace function we can convert boolean, num type to string and then pass to function.But since I'm doing encryption and then decryption, here after decrypted we get everything in string type, which I don't want.They need to be in their original type.So I think this will not work. So can anyone suggest any ideas and help me. Hope my question is clear. Any suggestions appreciated.
If you want to iterate and parse all properties of your JSON object, You could use Object.keys() this way :
obj = {
booleanVar : true,
numericVar : 125,
stringVar : "a string"
};
var iterate = JsonData => Object.keys(JsonData).forEach(key => console.log(JsonData[key]));
iterate(obj); // true
// 125
// a string
Remove your first if condition .
Example :
function iterate(JsonData) {
for (var exKey in JsonData) {
if (typeof JsonData[exKey] == "object") {
iterate(JsonData[exKey]);
} else {
JsonData[exKey] = encrypt(JsonData[exKey]);
}
}
}
searching for a function, which converts rhs to the type of lhs.
e.g.
var x=false // x is boolean now;
x=assign (x, "true"); //should convert "true" to boolean and return that
x=assign (x, 1); // dto, convert 1 to true
x=0 // x is number
x=assign (x, "123"); // should convert "123" to 123;
so such a function can be written, thats not the question. But: Is there somewhere a somehow complete implementation of such a thing? I started with something like that:
function assign (v, x) {
if (typeof v==typeof x) {
return x;
}
switch (typeof v) {
case 'boolean' : {
return x=='true'?true:false;
}
case 'number' : {
return parseFloat(x);
}
}
return "xxx";
}
var v=true;
var x='true';
var r1=assign (v, x);
console.log (typeof r1+ " "+r1);
v=10;
x="123";
var r1=assign (v, x);
console.log (typeof r1+ " "+r1);
which of course is not complete, but maybe shows what I'm goig for.
If you have objects x and y, you can pass y to the constructor of x, and if the constructor of x knows how to convert it, it will. E.g.
function y_in_type_of_x(x, y)
{
return x.constructor(y);
}
If you pass (1, '45') it will pass '45' to Number() you'll get 45. If you pass ('', 1) you'll get '1'. But it might give you some surprising results--the constructor Boolean(), for example, will convert anything other than 0 or false to true. Any string will convert to 'true'--even the string 'false'!
You should probably work out exactly which conversions you need and write them explicitly. I'd imagine it's a very limited subset of all the possible types. (Or re-examine why you are doing this at all, but I hate to be that guy!)
There are only three basic primitives you need to worry about typecasting in JS. Booleans, strings, and numbers (because I'm assuming you're doing this to check for equality === purposes? Maybe concatenation versus mathematical operations?)
Therefore there's three simple methods to do it:
Convert to a boolean - !!
var x = 1;
console.log(!!x); //true;
Convert to a string - concatenate an empty string
var x = 1;
console.log(x+''); //"1"
Convert to a number - put a + in front of it.
var x = "-123";
console.log(+x); //-123
Pretty straightforward.
What I essentially need to do is, given a json like
{
"1" : "a",
"7" : "something"
"3" : {
"1" : "blah"
}
}
Convert these to an array (say x).
x[1] = "a"
x[7] = "something"
x[3] = y (where y[1] = "blah")
You'll need to deserialize the JSON into a non-array object graph, and then copy the properties into arrays. I'm not aware of any shortcut for it.
The basic loop once you've deserialized the JSON into obj is roughly:
var ar;
var key;
ar = [];
for (key in obj) {
if (obj.hasOwnProperty(key)) {
ar[key] = obj[key];
}
}
...except you'll have to detect that obj[key] is an object and recurse, which I'll leave as an exercise for the reader.
Note that in JavaScript, arrays aren't really arrays. Depending on your use-case, you may not need to do the conversion from object to Array at all.
I'm pretty sure that in Javascript, you can access this:
x = {
"1" : "a",
"7" : "something",
"3" : {
"1" : "blah"
}
}
Like this:
alert( x["1"] );
which should alert "a". As people already mentioned in the comments above, an array in JS is an "object" already, and there isn't a difference between accessing them these two different ways.
Edit:
Yeah I just tested it and it works. Also, I tried this:
alert( x[1] );
That is, I tried it with the "number" 1, not the "string" "1". It still worked. Yes it's a very strange programming language.
I think this is pretty close:
function parse_obj(obj)
{
var array = [];
var prop;
for (prop in obj)
{
if (obj.hasOwnProperty(prop))
{
var key = parseInt(prop, 10);
var value = obj[prop];
if (typeof value === "object")
{
value = parse_obj(value);
}
array[key] = value;
}
}
return array;
}
http://jsfiddle.net/shaggyfrog/DFnnm/
This works for me:
var obj = JSON.parse('{"1":"a","7":"something","3":{"1":"blah"}}');
var keys = Object.keys(obj).sort();
// Make obj look like it's an array by taking the highest value
// key and using it to give obj a length property.
obj.length = parseInt( keys[keys.length] ) + 1;
var arr = Array.prototype.slice.call(obj, 0);
arr now looks like this:
[undefined, "a", undefined, Object, undefined, undefined, undefined, "something"]
Ok, so it hasn't turned the 'inner' JSON object into an array, but a quick recursive loop doing the same thing as above should sort that out.