Reputation: 109
I want to convert a string into an array. that works only with number value. in the following example the "border_color & border_style keys" returning NaN as value.
var str ="margin_top=5&margin_bottom=5&border_color=#dfdfdf&border_style=solid";
strToArray(str);
function strToArray(str){
str = str.replace(/\(|\)/g,'');
var arr = str.split('&');
var obj = {};
for (var i = 0; i < arr.length; i++) {
var singleArr = arr[i].trim().split('=');
var name = singleArr[0];
var value = singleArr[1]-0;
if (obj[name] === undefined) {
obj[name] = value;
}
alert(name+': '+value);
}
return obj;
}
Upvotes: 2
Views: 1658
Reputation: 575
Not really sure the way you want to return, but you can use: Object.values()
var str ="margin_top=5&margin_bottom=5&border_color=#dfdfdf&border_style=solid";
strToArray(str);
function strToArray(str){
str = str.replace(/\(|\)/g,'');
var arr = str.split('&');
var keys = []
var values = []
var obj = {};
for (var i = 0; i < arr.length; i++) {
var singleArr = arr[i].trim().split('=');
keys.push(Object.values(singleArr)[0])
values.push(Object.values(singleArr)[1])
}
alert(values)
alert(keys)
return obj;
}
Upvotes: 0
Reputation: 31712
The NaNs are comming from trying to convert the non-numeric values into numbers (ie, "#dfdfdf"
and "solid"
). Before trying to convert to numbers, check if the value string is valid or not using isNaN
:
var value = singleArr[1]; // don't convert yet
if (obj[name] === undefined) {
obj[name] = isNaN(value)? value: +value; // if value is not a valid number, then keep it as it is (a string). Otherwise, convert it to a number (using unary + which is shorter than substracting 0)
}
Working example:
var str ="margin_top=5&margin_bottom=5&border_color=#dfdfdf&border_style=solid";
strToArray(str);
function strToArray(str){
str = str.replace(/\(|\)/g,'');
var arr = str.split('&');
var obj = {};
for (var i = 0; i < arr.length; i++) {
var singleArr = arr[i].trim().split('=');
var name = singleArr[0];
var value = singleArr[1];
if (obj[name] === undefined) {
obj[name] = isNaN(value)? value: +value;
}
alert(name+': '+value);
}
return obj;
}
Upvotes: 4