string to list in special format in Javascript - javascript

I have a string containing comma separated names and optional values that seprated values like this:
var str = "PowerOn:On,ValidLocation, temp:25";
I want to convert it into objects or json that can access to values by name like this:
var a = {"PowerOn":"On", "ValidLocation":"true", "temp":25};
var result = a.PowerOn;
alert(result);
OR
var a = {"PowerOn":"On", "ValidLocation":"true", "temp":25};
var result = a["PowerOn"];
alert(result);
Note 1: If a name doesn't have value it be true by default.
Update:
Note 2 :If a name doesn't exist in list the value of it be false: ex:
var a = {"PowerOn":"On", "ValidLocation":"true", "temp":25};
var result = a.Alarm
//result must be false

var str = "PowerOn:On,ValidLocation, temp:25",
arr = str.split(','),
obj = {}
for (var i=0; i<arr.length; i++) {
var parts = arr[i].split(':');
obj[parts[0]] = parts[1] || true;
}
JSFIDDLE

Assuming the delimiters remain as such, Does this work for you :
var result = {};
"PowerOn:On,ValidLocation, temp:25".split(",").forEach(function(i) {
result[(i=i.split(":"))[0]]=i[1] || true;
});
// result : {PowerOn: "On", ValidLocation: true, temp: "25"}
To the second part of you question use !!result.Alarm which should be false.

Related

How to convert array to object then assign to new variable

I want to convert data stored in one variable from an array to an object, then assign that converted data to another variable.
For example, take:
options = ["226:39"];
and convert ["226:39"] to {"226":"39"}, then assign the converted data to the convertedOptions variable.
How would I do that?
While the other answers are correct for the sample value you mentioned in the question, using substring instead of split will handle the case where the value may need to contain a ":" character.
var options = ["226:39", "ratio:226:39"];
var convertedOptions = {};
for(var i = 0; i < options.length; i++){
var separatorIndex = options[i].indexOf(":");
if(separatorIndex > -1) {
var name = options[i].substring(0, separatorIndex);
var value = options[i].substring(separatorIndex + 1, options[i].length);
convertedOptions[name] = value;
}
}
console.log(convertedOptions);
You can split the string using the : separator, create your convertedOptions object, and then assign.
var options = ['226:39'];
var splitOptions = options[0].split(':');
var convertedOptions = {};
convertedOptions[splitOptions[0]] = splitOptions[1];
console.log(convertedOptions);
You can do it by spliting the element of options by ':':
var options = ["226:39"];
convertedOptions = {};
var el = options[0].split(':');
convertedOptions[el[0]] = el[1];
console.log(convertedOptions);
OR:
var options = ["226:39"];
convertedOptions = {};
var [prop, value] = options[0].split(':');
convertedOptions[prop] = value;
console.log(convertedOptions);
OR:
var options = ["226:39"];
var [prop, value] = options[0].split(':');
convertedOptions = { [prop]: value };
console.log(convertedOptions);
You could split the string and map an object for each element of options for a new property.
var options = ["226:39"],
convertedOptions = Object.assign(
...options.map(a => (([k, v]) => ({ [k]: v }))(a.split(':')))
);
console.log(convertedOptions);
Use String#replace to format the string as JSON, and then convert to an object using JSON#parse:
var options = ["226:39"];
var convertedOptions = JSON.parse(options[0].replace(/([^:]+):([^:]+)/, '{"$1":$2}'));
console.log(convertedOptions);

Extracting values from an example string given a simple template

I want to write a function such as:
function extract(template, example){
//some magic
return obj;
}
That given an input like the following:
var template = "/some/path/{param_one}/{another_param}/etc?arg1={value}";
var example = "/some/path/foo/bar/etc?arg1=baz";
Would return this object:
{param_one: "foo", another_param: "bar", value: "baz"}
I don't have control over the template nor the example (e.g. I can't change the template to be a regex with named capture groups). What I can safely assume is that the given example will match the template.
As a start, I was able to extract the keys with this:
var re = /\{(.+?)\}/g;
var match;
do {
match = re.exec(template)
if (match) {
console.log(match[1]);
}
} while (match);
I use regex and replace to solve:
function extract(template, example){
//some magic
var re = /(?:([^\{]*)\{([^\}]*)\})/g;
var result = example;
var params = [];
var match, values, obj = {};
do {
match = re.exec(template)
if (match) {
result = result.replace(match[1], '|');
params.push(match[2]);
}
} while (match);
values = result.split('|');
for(var i=0;i < params.length; i++) {
obj[params[i]] = values[i+1];
}
return obj;
}
First, it get params part and text part use regex, then it replace all text part with | and store key to params array.
Finally, it loops through params array and match value splited from above
Hope this help
I would break this into two parts - build a template object, then use that template object to parse your string(s). The following function buildTemplate(pattern) returns a template object. You can then use this object to parse as many strings as you need, for example buildTemplate(pattern).parse(string) or even var parser = buildTemplate(pattern); var parameters = parser.parse(string);.
function buildTemplate(pattern) {
return (function(pattern) {
function splitString(string) {
return string.split(/[/?&]+/);
}
var glob = {};
glob.parts = splitString(pattern).map(function(part) {
var trimmedPart = part.replace(/^\{|\}$/g, '');
var isLiteral = part.length !== trimmedPart.length + 2;
return {
isLiteral: isLiteral,
value: isLiteral ? part : trimmedPart:
};
});
glob.parse = function(string) {
var stringParts = splitString(string);
if (stringParts.length !== glob.parts.length) {
return null;
}
var params = {};
for (var i = 0; i < stringParts.length; i++) {
if (blob.parts[i].isLiteral) {
if (blob.parts[i].value !== stringParts[i]) {
return null;
}
} else {
params[blob.parts[i].value] = stringParts[i];
}
}
return params;
}
return glob;
})(pattern);
}
Note: This code is completely untested. Let me know if something doesn't work as intended.

Convert string to separate arrays

str = "books:book1, books:book2, houses:house1, houses:house2, person:james";
I want to convert above string to separate arrays or arrays within an object, something like:
books = ["book1","book2"];
houses = ["house1","house2"];
person = ["james"];
How can I do this in JavaScript?
var string = "books:book1, books:book2, houses:house1, houses:house2, person:james";
var hash = {};
var splitByComma = string.split(',');
function addKeyByVal( key, val ){
if(!hash[key]) hash[key] = [];
hash[key].push(val);
}
for( var s in splitByComma ){
var splitByColon = splitByComma[s].split(":");
addKeyByVal(splitByColon[0], splitByColon[1]);
}
console.log(hash);
You probably want an object, with keys containing the arrays.
var str = "books:book1, books:book2, houses:house1, houses:house2, person:james";
var obj = str.split(',').reduce( (a,b) => { // split the string on comma
var parts = b.trim().split(':'); // split the parts on colon
if (! (parts[0] in a) ) a[parts[0]] = []; // if no key, create an array
a[parts[0]].push(parts[1]); // push the value to the array
return a; // return the object for next iteration
}, {})
console.log(obj)
You can split on ', ' and reduce to an object containing key: []:
const string = "books:book1, books:book2, houses:house1, houses:house2, person:james";
const output = string.split(', ').reduce((obj, cur) => {
let [category, value] = cur.split(':');
if (!Array.isArray(obj[category])) {
obj[category] = [value];
} else {
obj[category].push(value);
}
return obj;
}, {});
console.log(output);
Something like this:
var string = "books:book1, books:book2, houses:house1, houses:house2, person:james";
var books = [];
var houses = [];
var person = [];
string.split(", ").forEach(function(e) {
switch (e.split(":")[0]) {
case "books":
books.push(e.split(":")[1]);
break;
case "houses":
houses.push(e.split(":")[1]);
break;
case "person":
person.push(e.split(":")[1]);
break;
}
});
The code goes like this:
Make three new arrays for books, houses, and person.
Split the string into an array, separating by ,.
Go through each element in the new array and split it into another array, separating by :
If the string on the left is books, houses, or person then append the string on the right to the books, houses, or person arrays, respectively.
This will put create global variables for you leveraging the window, but for the love of god please don't -- just use an object. While this answer is what you asked for, the other answers are what you really want.
var str = "books:book1, books:book2, houses:house1, houses:house2, person:james";
var splitStr = str.split(',');
var i;
var key;
var val;
var temp;
for (i=0; i<splitStr.length; i++) {
temp = splitStr[i].split(':');
key = temp[0].replace(/ /g,'');
val = temp[1];
if (!window[key]) {
window[key] = [];
}
window[key].push(val);
}
console.log(books, houses, person);
First, you can use the split string method twice to break down the data, then to make them into (almost) global variables, you can set them as window properties, however this can be dangerous if the values passed interfere with the existing properties.
var pairs = str.split(", ");
for(var i = 0; i < pairs.length; i++) {
var key = pairs[i].split(":")[0];
var val = pairs[i].split(":")[1];
if(window.hasOwnProperty(key)) {
window[key].push(val);
}
else {
window[key] = [];
window[key].push(val);
}
}
This method is not recommended for cases where the source of the string is unknown, as it directly modifies window properties, some of which may cause unexpected behaviour if overwritten.
RegExp method.
var string = "books:book1, books:book2, houses:house1, houses:house2, person:james",
arr = string.split(', '), obj = {}, res = [];
arr.forEach(function(v){
var array = [],
elem1 = v.match(/\w+(?=:)/),
elem2 = v.match(/(?:)\w+/g)[1];
if (!obj[elem1]){
obj[elem1] = [];
obj[elem1].push(elem2);
} else {
obj[elem1].push(elem2);
}
});
console.log(obj);

Loop thru a string with numbers and symbols & push to array

I'm trying to loop thru a string with numbers that has a symbol inside, I want the numbers before the symbol to be pushed to an array then the symbol to another array and then get the rest of the numbers after the symbol pushed to a 3rd array.
var myString = "1234*5678";
var number1 = [];
for (i = 0; i < myString.length; i++) {
if (isNaN(myString[i]) === false) {
var firstSet = number1.push(myString[i]);
}
};
var mySymbol = [];
for (j = number1[0]; j < myString.length; j++) {
if (isNaN(myString[j]) === true) {
var mathematics = mySymbol.push(myString[j])
document.write(mySymbol[0])
}
};
when I document.write the "mySymbol" variable it gives the desired result, but when I call the "number1" variable it gives me the numbers from before and after the symbol I only want the numbers before the symbol to be pushed to the array, also how do I write the 3rd loop to get the numbers after the symbol pushed to a new array?
try
var arr=[[],[],[]]
index = 0
"1234*5678".split('').forEach(function(e){
if(parseInt(e)){
arr[index].push(e);
}else{
index ++;
arr[index++].push(e)
}
});
document.write('First Array ' +arr[0] + '<br>');
document.write('Secont Array ' +arr[1] + '<br>');
document.write('Third Array ' +arr[2]);
You could try using:
var myString = '1234*5678';
var resultArr = myString.match(/([a-zA-Z0-9]+)([^a-zA-Z0-9])([a-zA-Z0-9]+)/);
To get the string before symbol:
var myFirstSet = resultArr[1];
To get symbol:
var mySymbol = resultArr[2];
To get the string after symbol:
var mySecondSet = resultArr[3];
To convert each of these three groups into their own arrays:
var result = [];
resultArr
.slice(1)
.forEach(
function(s){
result.push(s
.split('')
.map(
function(n){
return parseInt(n) || n;
}
)
)
}
);
The following code accomplishes the goal:
var str = '1234*5678';
var arr = str.match(/([a-zA-Z0-9]+)|\*/g);
console.log(arr[0], arr[1], arr[2]);
http://jsfiddle.net/hp2ohvzb/

Extract the key and value from a string separated by pipe using javascript

I have a string which is in pipe separated format as shown below
var request = "Country : India|Location : Mumbai|Attachment:Photo.png";
When I do a split it gives the following as output
var p = request.split("|");
(
"Country : India",
"Location : Mumbai",
"Attachment : Photo.png"
)
How do I extract the key and its respective value?
The entire value is in quotes.
Please help
You could Array.reduce on request.split("|") and return key value based object.
var obj = request.split("|").reduce(function(o, c){
var arr = c.split(":");
return o[arr[0].trim()] = arr[1].trim(), o; // comma operator
},{});
When you log it by console.log(obj), you get
{ Country: "India", Location: "Mumbai", Attachment: "Photo.png" }
There you go:
function getKeyvalue() {
var request = "Country : India|Location : Mumbai|Attachment:Photo.png";
var arr = request.split("|");
for (var i in arr) {
var newarr = arr[i].split(":");
var key = newarr[0]; // key
var value = newarr[1]; // value
}
}
You can use the code to store all keys in key and values in value
The key and value can be obtained by using the same index
var request = "Country : India|Location : Mumbai|Attachment:Photo.png";
var p = request.split("|");
var key = [];
var value = [];
for(var i=0; i<p.length; i++){
var pmap = p[i].split(":");
key = pmap[0];
value = pmap[1];
}
Posting this as an alternative.
Using maps would be a better option.

Categories