get key value pairs out from the string javascript - javascript

If my string looks like this
"<First key="ab" value="qwerty"/>
<First key="cd" value="asdfg"/>
<First key="ef" value="zxcvb"/>"
and I want to get data out in the format
ab:"qwerty"
cd:"asdfg"
ef:"zxcvb"
How should I write the JS ?

It would be useful to see the code you've attempted, but here's a way you could achieve it:
Use a regex to pick out the relevant parts of the string.
var regex = /key="([a-zA-Z]+)" value="([0-9a-zA-Z\-\.]+)"/;
Function to remove empty elements.
var notEmpty = function (el) { return el !== ''; };
split the string into an array on the carriage return and use reduce to build the new object by applying the regex to each array element.
var out = str.split('\n').filter(notEmpty).reduce(function(p, c) {
var match = c.match(regex);
p[match[1]] = match[2];
return p;
}, {});
OUTPUT
{
"ab": "qwerty",
"cd": "asdfg",
"ef": "zxcvb"
}
DEMO

Please, make your question more clear(What result data type would you like to get?), or try these functions:
var string = '<First key="ab" value="qwerty"/><First key="cd" value="asdfg"/><First key="ef" value="zxcvb"/>'
var ParseMyString1 = function(str){
var arr = str.split(/[</>]+/); //"
//console.log(arr);
var result = [];
for (var i =0; i<arr.length; i++) {
var subStr=arr[i];
if (subStr.length!==0) {
var subArr = subStr.split(/[\s"=]+/); //"
//console.log(subArr);
var currObj = {};
var currKey = "";
var currVal = "";
for (var j =0; j<arr.length; j++) {
if (subArr[j]=="key"){
currKey = subArr[++j];
}else if (subArr[j]=="value"){
currVal = subArr[++j];
}
};
currObj[currKey] = currVal;
result.push(currObj);
};
};
console.log("ParseMyString1:");
console.log(result);
};
var ParseMyString2 = function(str){
var arr = str.split(/[</>]+/); //"
//console.log(arr);
var resultObj = {};
for (var i =0; i<arr.length; i++) {
var subStr=arr[i];
if (subStr.length!==0) {
var subArr = subStr.split(/[\s"=]+/); //"
//console.log(subArr);
var currKey = "";
var currVal = "";
for (var j =0; j<arr.length; j++) {
if (subArr[j]=="key"){
currKey = subArr[++j];
}else if (subArr[j]=="value"){
currVal = subArr[++j];
}
};
resultObj[currKey] = currVal;
};
};
console.log("ParseMyString2:");
console.log(resultObj);
};
$(document).ready(function(){
ParseMyString1(string);
ParseMyString2(string);
});
These functions return results as below (array of objects):
ParseMyString1:
[{ab:"qwerty"},{cd:"asdfg"},{ef:"zxcvb"}]
ParseMyString2:
{ab:"qwerty",cd:"asdfg",ef:"zxcvb"}

First, your string is not valid (double quotes within double quotes). You'd either need to escape the inner quotes with \" or just replace the inner quotes with single quotes.
But, assuming that your data was always going to be in the format you show, this simple code will extract the data the way you want:
var data = "<First key='ab' value='qwerty'/><First key='cd' value='asdfg'/><First key='ef' value='zxcvb'/>";
data = data.replace(/<First /g, " ").replace(/\/>/g, "").replace(/key=/g, "").replace(/value=/g, "").trim();
var ary = data.split(" ");
var iteration = "";
var result = "";
for(var i = 0; i < ary.length; i+=2){
iteration = ary[i].replace(/'/g, "") + ":" + ary[i+1].replace(/'/g, "\"");
alert(iteration);
result += " " + iteration;
}
alert("Final result: " + result);

Your input is a kind of XML. The best way is to treat it as such. We will parse it as XML, but to do so, we need to first wrap it in a root element:
var str = "<Root>" + input + "</Root>"
We parse it with
var parser = new DOMParser();
var dom = parser.parseFromString(str, "text/xml");
Get the document element (Root):
var docelt = dom.documentElement;
Now we can loop over its children and build our result, using standard DOM access interfaces like getAttribute:
var result = {};
var children = docelt.children;
for (var i = 0; i < children.length; i++) {
var child = children[i];
result[child.getAttribute('key')] = child.getAttribute('value');
}
> result
< Object {ab: "qwerty", cd: "asdfg", ef: "zxcvb"}
You can replace the above looping logic with reduce or something else as you prefer.
This approach has the advantage that it takes advantage of the built-in parser, so we don't end up making assumptions about the syntax of XML. For instance, the regexp suggested in another answer would fail if the attributes had spaces before or after the equal sign. It would fail if the values contained Unicode characters. It would fail in odd ways if the XML was malformed. And so on.

Related

Creating an array without hard-coding

I'm trying to create an array of strings and produce the possibilities by the length of array string. For example:
var someStr = ["a","b","c","d"];
//I want to produce this outcome
a
ab
abc
abcd
b
bc
bcd
c
cd
d
I know I can get the # of possibilities for "a" only by this way:
var numCombinations = 0;
var comboString = '';
var outcome = [];
for(var i = 0; i < someStr.length; i++){
comboString += someStr[i];
outcome[i] = comboString;
numCombinations += i; //# of combinations from above
}
But how would I continue with these variables for the left over possibilities? I've thought of creating nested for-loops again and again but that would eventually lead to the (n)th length with hard-coding. Would there be any method(s) to create this and store all the possibilities to the (n)th length?
Hope this help.
function getComboStringListFromIdx(arr, idx){
var result = [];
var comboString = '';
for(var i=idx; i<arr.length; i++){
comboString += arr[i];
result.push(comboString);
}
return result;
}
var someStr = ['a','b','c','d'];
var outCome = [];
for(var i = 0; i<someStr.length; i++){
outCome = outCome.concat(getComboStringListFromIdx(someStr, i));
}
I will also use nested for-loop ! One is normal looping and other is to skip less than current index from first loop !!
var someStr = ["a","b","c","d"];
for(var i = 0;i < someStr.length;i++) {
output(i);
}
function output(index) {
var str = "";
for(var j in someStr) {
if(j < index) {
continue;
}
str += someStr[j];
console.log(str);
}
}
This solution uses a nested for loop and skips concatenation on the first element of the nested for loop.
var arr = ["a","b","c","d"];
for(var i=0;i<arr.length;i++){
var str = arr[i];
for(var j=i;j<arr.length;j++){
if(i!==j)
str+=arr[j];
console.log(str);
}
}
https://jsfiddle.net/fmy539tj/

How to separate the string into two categories in jstl?

i have a string as,
String value = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
Now i need split the names and those values.
I am unable to identify what to do.
I need to print the values as
Output
---
-----------------------------
' Name ' value '
'------------'--------------'
' Bhavani ' 12 '
' Pallavi ' 13 '
' Charanya ' 14 '
' ' '
----------------------------'
I think it can be done in jstl level..
But can anyone help me how to split that string.
you can use str.replace to create an object:
strvalue = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14"
obj={};
strvalue.replace(/(\w+)<>(\w+)/g,function(_,m1,m2){
obj[m1]=m2
})
console.log(obj)
This should do it:
var str = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
str = str.split('<<>>')
for(var i = 0; i < str.length; i++) {
str[i] = str[i].split('<>');
}
alert(str.join("\n"));
first split with <<>>
than split wiht <>
so you will get array with Bhavani , 12 in two indexes.
its simple to show in any way on view.
Personally, I'd store the key-value pairs in an object:
var myObj = {};
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
var stringArray = string.split('<<>>');
for(i in stringArray){
var key = stringArray[i].split('<>')[0];
var value = stringArray[i].split('<>')[1];
myObj[key] = value;
}
console.log('My object looks like', myObj);
Here is my solution, you'll get an array of objects with a name and value inside each object:
let value = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
let splittedString = value.split("<<>>");
let names = [];
splittedString.forEach(function(value) {
let splittedProps = value.split("<>");
names.push({
name: splittedProps[0],
value: splittedProps[1]
});
});
console.log(names);
var str = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
var strArr = str.split("<<>>");
var result = {};
for(var i in strArr){
var p = strArr[i].split("<>");
result[p[0]] = p[1];
}
console.log(result);
First split with <<>>
then split string with <>
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
string = string.split('<<>>');
for(var i = 0; i < string.length; i++) {
string[i] = string[i].split('<>');
}`
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
string = string.split('<<>>');
for(var i = 0; i < string.length; i++) {
string[i] = string[i].split('<>');
}
alert(string.join("\n"));
`
var str = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
var txt = str.split("<<>>").join("|").split("<>").join("|").split("|")
var object=[];
for (var i=0; i<txt.length;i=i+2){
object.push({Name:txt[i],Value:txt[i+1]});
}
console.log(object);

Javascript, consolidate array elements

I'm stuck of finding a way to consolidate array elements.
so my array is in format of [id1:port1,id2:port2,id1:port3,id2:port4,id5:port5...] where each element has 2 portions. The id portion is not unique. what I try to consolidate is to create a new array will have data like [id1#port1:port3,id2#port2:port4,id5#port5]
I tried code below but it didn't get me too far. can any guru help me out?
var orinString = "id1:port1,id2:port2,id1:port3,id2:port4,id5:port5";
var newArray1 = orinString.split(",");
var newArray2 = orinString.split(",");
var newArray3 = [];
for (x=0; x<=newArray1.length-1; x++) {
for (y=0; y<= newArray2.length-1; y++) {
if ((newArray1[x].split(":")[0] == newArray2[y].split(":")[0]) && (newArray1[x].split(":")[1] != newArray2[y].split(":")[1])) {
newArray3.push(newArray1[x].split(":")[0] +"#"+ newArray1[x].split(":")[1]);
}
}
}
for (z=0; z<=newArray3.length; z++) {
gs.log("show me the result " +newArray3[z]);
}
is it that you want:
var orinString = "id1:port1,id2:port2,id1:port3,id2:port4,id5:port5";
var arr1 = orinString.split(",");
var temp= "";
var newStr = "";
arr1.sort();
for(i=0; i< arr1.length; i++) {
var item = arr1[i].split(':');
if(item[0] !== temp || temp === "") {
newStr += "," + item[0] + "#" + item[1];
} else {
newStr += ":"+item[1];
}
temp = item[0];
}
console.log(newStr.substring(1));
A typical way to solve a problem like this is
Convert them into workable values
Populate some kind of lookup table
Output the results of this lookup table
For example
var orinString = "id1:port1,id2:port2,id1:port3,id2:port4,id5:port5";
var idsAndPorts = orinString.split(",");
// Populate a key lookup
var hashTable = {};
idsAndPorts.forEach(function(s) {
var splitValue = s.split(':');
var key = splitValue[0];
var value = splitValue[1];
if(hashTable[key]) {
hashTable[key].push(value);
} else {
hashTable[key] = [value];
}
});
// Now convert it back into an array again
var finalArray = [];
for(var k in hashTable) {
finalArray.push(k + '#' + hashTable[k].join(','));
}
// View the results
finalArray.forEach(function(f) {
console.log(f);
})
This does not guarantee the final array will be sorted, but you can sort it yourself if you wish.

How to build an array from a string in javascript?

I am trying to grab some values out of a sting that looks like this:
W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748
I want to make an array of all the keys and another array of all the values i.e. [W1, URML, MH…] and [0.687268668116, 0.126432054521...]
I have this snippet that does the trick, but only for the first value:
var foo = str.substring(str.indexOf(":") + 1);
Use split().
Demo here: http://jsfiddle.net/y9JNU/
var keys = [];
var values = [];
str.split(', ').forEach(function(pair) {
pair = pair.split(':');
keys.push(pair[0]);
values.push(pair[1]);
});
Without forEach() (IE < 9):
var keys = [];
var values = [];
var pairs = str.split(', ');
for (var i = 0, n = pairs.length; i < n; i++) {
var pair = pairs[i].split(':');
keys.push(pair[0]);
values.push(pair[1]);
};
This will give you the keys and values arrays
var keys = str.match(/\w+(?=:)/g),
values = str.match(/[\d.]+(?=,|$)/g);
RegExp visuals
/\w+(?=:)/g
/[\d.]+(?=,|$)/g
And another solution without using regexp
var pairs = str.split(" "),
keys = pairs.map(function(e) { return e.split(":")[0]; }),
values = pairs.map(function(e) { return e.split(":")[1]; });
JSFiddle
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748";
var all = str.split(","),
arrayOne = [],
arrayTwo = [];
for (var i = 0; i < all.length; i++) {
arrayOne.push(all[i].split(':')[0]);
arrayTwo.push(all[i].split(':')[1]);
}
parse the string to an array
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275";
var tokens = str.split(",");
var values = tokens.map(function (d) {
var i = d.indexOf(":");
return +d.substr(i + 1);
});
var keys = tokens.map(function (d) {
var i = d.indexOf(":");
return d.substr(0, i);
});
console.log(values);
console.log(keys);
http://jsfiddle.net/mjTWX/1/ here is the demo

how can I parse json with multiple lines

I have the following JSON:
[{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}]
I need to extract all "phoneNumber" using a js function.
I'm testing from using html and my function is not so good:
function getNumbers(strJSON)
{
strJSON = "[{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557704\",\"returnCode\":\"0\"},{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557705\",\"returnCode\":\"0\"},{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557706\",\"returnCode\":\"0\"}]";
var len = strJSON.length;
var begin_index = strJSON.indexOf("returnCode") - 2;
var last_index = len - 1;
var string_toSplit = strJSON.substring(begin_index, last_index);
var string_splitted = string_toSplit.split("{");
var out="";
alert(strJSON);
alert("string_splitted");
alert(string_splitted);
for ( var i = 0; i < string_splitted.length; i++)
{
if (string_splitted[i].charAt(string_splitted[i].length - 1) === ",")
{
string_splitted[i] = string_splitted[i].slice(0, -1);
}
var json = "{" + string_splitted[i];
var obj = JSON.parse(json);
if (i == string_splitted.length)
{
out = out + obj.phoneNumber;
}
else
{
out = out + obj.phoneNumber + ",";
}
}
return out;
}
For modern browsers you can use the .map() method
var j = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var phones = j.map(function(item){return item.phoneNumber});
Update
After seeing your code (do not try to manually split/parse the json string.. use the JSON.parse method) you should use
function getNumbers(strJSON)
{
var myJson = JSON.parse( strJSON );
return myJson.map(function( item ){ return item.phoneNumber}).join(',');
}
Update: An even better way:
function getNumbers(strJSON)
{
var obj = JSON.parse(strJSON);
return obj.map(x => x.phoneNumber).join(", ")
}
Original Post:
A straight forward method is to just iterate over every object in the array and take the values out individually.
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var phoneNumbers = [];
for (var i = 0; i < info.length; i++)
{
phoneNumbers.push(info[i].phoneNumber);
}
console.log(phoneNumbers);
http://jsfiddle.net/hX69r/
UPDATE:
http://jsfiddle.net/hX69r/1/
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var infoString = JSON.stringify(info); //this just turns the object array 'info' into a string
var numbers = getNumbers(infoString);
console.log(numbers);
function getNumbers(strJSON)
{
var obj = JSON.parse(strJSON);
var phoneNumbers = [];
for (var i = 0; i < obj.length; i++)
{
phoneNumbers.push(obj[i].phoneNumber);
}
return phoneNumbers.join(", ");
}
Additional Update:
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var infoSingle = {"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"};
console.log(info.length); // prints 4; so you know it has the []
console.log(infoSingle.length); // prints undefined; so you know it doesn't have []
Do not try to re-invent the wheel.
There are many ways to parse JSON already:
Use JSON.parse.
Use jQuery.parseJSON

Categories