Spliting based on comma and then space in JavaScript - javascript

aaa 3333,bbb 5,ccc 10
First i need to split based on Comma and the i need to split based on space to make it key value pair... how do i do in JavaScript.

var pairs = {};
var values = "aaa 3333,bbb 5,ccc 10".split(/,/);
for(var i=0; i<values.length; i++) {
var pair = values[i].split(/ /);
pairs[pair[0]] = pair[1];
}
JSON.stringify(pairs) ; //# => {"aaa":"3333","bbb":"5","ccc":"10"}

Use the split method:
var items = str.split(',');
for (var i = 0; i < items.length; i++) {
var keyvalue = items[i].split(' ');
var key = keyvalue[0];
var value = keyvalue[1];
// do something with each pair...
}

What about something like this :
var str, arr1, arr2, i;
str = 'aaa 3333,bbb 5,ccc 10';
arr1 = str.split(/,/);
for (i=0 ; i<arr1.length ; i++) {
arr2 = arr1[i].split(/ /);
// The key is arr2[0]
// the corresponding value is arr2[1]
console.log(arr2[0] + ' => ' + arr2[1]);
}

Code says more than a thousand words.
var str = "aaa 3333,bbb 5,ccc 10";
var spl = str.split(",");
var obj = {};
for(var i=0;i<spl.length;i++) {
var spl2 = spl[i].split(" ");
obj[spl2[0]] = spl2[1];
}

var s = 'aaa 3333,bbb 5,ccc 10';
var tokens = s.split(',');
var kvps = [];
if (tokens != null && tokens.length > 0) {
for (var i = 0; i < tokens.length; i++) {
var kvp = tokens[i].split(' ');
if (kvp != null && kvp.length > 1) {
kvps.push({ key: kvp[0], value: kvp[1] });
}
}
}

Use String.split() : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
var theString = 'aaa 3333,bbb 5,ccc 10';
var parts = theString.split(',');
for (var i=0; i < parts .length; i++) {
var unit = parts.split(' ');
var key = unit[0];
var value = unit[1];
}

// this thread needs some variety...
function resplit(s){
var m, obj= {},
rx=/([^ ,]+) +([^,]+)/g;
while((m= rx.exec(s))!= null){
obj[m[1]]= m[2];
};
return obj;
}
var s1= 'aaa 3333,bbb 5,ccc 10';
var obj1=resplit(s1);
/* returned value: (Object)
{
aaa: '3333',
bbb: '5',
ccc: '10'
}
*/

Related

How to clean , from a given string?

I have data like this.
var abc =",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
abc = abc.split(",");
let stub={};
var results=[];
var key=["name","value","acc"];
var i=0;
var j=0;
for( var i = 0 ; i <abc.length - 1;i++){
stub[key[j]=abc[i];
j++
if(j==3){
results.push(stub);
stub={};
j=0;
}
}
abc = results;
I would like to get those values arranges in form of array of object having those 3 keys:
output should be:
abc = [{"name": "paul", "value": "2000","acc":"12sc21"},{"name":"logan","value":"123","acc":"21sdf34"},{"name":"vfsarwe","value":"456456","acc":"32fd23"}];
but not able to get the desired output. this output only comes when string don't have ,,,,,, in starting. But the data i'm getting is sometimes having ,,,,, in stating.
You can use abc.replace(/(^[,\s]+)/g, '') to remove leading commas or whitespace from the String. Your for loop is also not running for long enough; it is looping until there is only one element left in the Array and then stopping.
Change
for(var i = 0 ; i < abc.length-1; i++)
To
for(var i = 0 ; i < abc.length; i++)
var abc =",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
abc = abc.replace(/(^[,\s]+)|([,\s]+$)/g, '').split(",");
let stub={};
var results=[];
var key=["name","value","acc"];
var i=0;
var j=0;
for(var i = 0 ; i < abc.length; i++){
stub[key[j]]=abc[i];
j++
if(j==3){
results.push(stub);
stub={};
j=0;
}
}
abc = results;
console.log(abc);
You can use .replace(/^\,+/, '') to remove all leading commas, then split by comma to get an array, then loop over this array using 3 as step and construct your results:
var abc = ",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var arr = abc.replace(/^\,+/, '').split(",");
var results = [];
for (var i = 0; i < arr.length; i = i + 3) {
results.push({
"name": arr[i],
"value": arr[i + 1],
"acc": arr[i + 2]
});
}
Demo:
var abc = ",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var arr = abc.replace(/^\,+/, '').split(",");
var results = [];
for (var i = 0; i < arr.length; i = i + 3) {
results.push({
"name": arr[i],
"value": arr[i + 1],
"acc": arr[i + 2]
});
}
console.log(results);
You are on the right track with splitting your data on ,. You can then split the data in to chunks of 3, and from there map each chunk to a dict.
var data = ",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var split = data.split(",");
var chunked = [];
while (split.length) {
chunked.push(split.splice(0,3));
}
var res = chunked.map((i) => {
if (!i[0] || !i[1] || !i[2]) {
return null;
}
return {
name: i[0],
value: i[1],
acc: i[2]
};
}).filter((i) => i !== null);
console.log(res);
You can use:
abc.replace(/,+/g, ',').replace(/^,|,$/g, '').split(',');
The regEx replaces removes the data that you are not interested in before performing the split.
or
abc.split(',').filter(Boolean);
The filter(Boolean) will remove the items from the array that could be the equivalent of false once the array has been instantiated.
EDIT:
var abc =",,,,,,,,,,,,,,,paul,2,000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var array = abc.replace(/,+/g, ',').replace(/^,|,$/g, '').split(/,([0-9,]+),/);
array = array.filter(Boolean).reduce(function(acc, item) {
if (item.match(/^[0-9,]+$/)) {
acc.push(item);
} else {
acc = acc.concat(item.split(','));
}
return acc;
}, []);

Alternately Join 2 strings - Javascript

I have 2 strings and I need to construct the below result (could be JSON):
indexLine: "id,first,last,email\n"
dataLine: "555,John,Doe,jd#gmail.com"
Result: "id:555,first:john,....;
What would be the fastest way of joining alternately those 2 strings?
I wrote this - but it seems too straight forward:
function convertToObject(indexLine, dataLine) {
var obj = {};
var result = "";
for (var j = 0; j < dataLine.length; j++) {
obj[indexLine[j]] = dataLine[j]; /// add property to object
}
return JSON.stringify(obj); //-> String format;
}
Thanks.
var indexLine = "id,first,last,email";
var dataLine = "555,John,Doe,jd#gmail.com";
var indexes = indexLine.split(',');
var data = dataLine.split(',');
var result = [];
indexes.forEach(function (index, i) {
result.push(index + ':' + data[i]);
});
console.log(result.join(',')); // Outputs: id:555,first:John,last:Doe,email:jd#gmail.com
If you might have more than one instance of your object to create, you could use this code.
var newarray = [],
thing;
for(var y = 0; y < rows.length; y++){
thing = {};
for(var i = 0; i < columns.length; i++){
thing[columns[i]] = rows[y][i];
}
newarray.push(thing)
}
source

JavaScript making an array of key value object from a string

I have a string like this
var information = 'name:ozil,age:22,gender:male,location:123 street';
I want to make an array of key value object like this
var informationList=[
{
'key':'name',
'value':'ozil'
},
{
'key':'gender',
'value':'male'
},
{
'key':'location',
'value':'123 street'
},
]
Using split and map:
var information = 'name:ozil,age:22,gender:male,location:123 street',
result = information.split(',').map(function(item){
var arr = item.split(':');
return {
key: arr[0],
value: arr[1]
}
});
document.write(JSON.stringify(result));
You can try this:
var list = [];
var pairs = information.split(',');
for (var i = 0; i < pairs.length; i++) {
var p = pairs[i].split(':');
list.push({
key: p[0],
value: p[1]
});
}
This should do it:
var input = "name:ozil,age:22,gender:male,location:123 street";
var temp = input.split(",");
var result = [];
for(var i=0; i < temp.length; i++) {
var temp2 = temp[i].split(":");
result.push({key:temp2[0], value:temp2[1]});
}
console.log(result);
result now contains what you specified.

String to Object literal

Is it possible to convert a string var:
data="data1,data2,data3,data4"
to an object literal
data={
"data1":"data2",
"data3":"data4"
}
Thank you!
var arr = data.split(',');
var parsedData = {};
for (var i = 0; i < arr.length; i += 2) {
parsedData[arr[i]] = arr[i + 1];
}
This is trivial:
function object_from_string(str) {
var parts = str.split(','),
obj = {};
for(var i = 0, j = parts.length; i < j; i+=2;) {
obj[parts[i]] = parts[i+1];
}
return obj;
}
var data = "data1,data2,data3,data4";
var obj = object_from_string(data);
for(var k in obj) {
if(obj.hasOwnProperty(k)) {
console.log(k + ' = ' + obj[k]);
}
}
Output:
data1 = data2
data3 = data4

Make a JavaScript array from URL

I need to make a Javascript array from URL, eg:
turn this:
http://maps.google.com/maps/api/staticmap?center=Baker Street 221b, London&size=450x450&markers=Baker Street 221b, London&sensor=false
Into something like:
array['center'] = Baker Street 221b, London
array['size'] = 450x450
// and so on...
I need to make this serializaion/unserialization work both ways (url to array and array to the part of the url). Are there some built-in functions that do this?
Thanks in advance!
URL to array: (adapted from my answer here)
function URLToArray(url) {
var request = {};
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
if(!pairs[i])
continue;
var pair = pairs[i].split('=');
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return request;
}
Array to URL:
function ArrayToURL(array) {
var pairs = [];
for (var key in array)
if (array.hasOwnProperty(key))
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(array[key]));
return pairs.join('&');
}
the above function URLToArray is not working when url string has elem[]=23&elem[]=56..
see below the adapted function... hope it is working - not 100% tested
function URLToArray(url) {
var request = {};
var arr = [];
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
//check we have an array here - add array numeric indexes so the key elem[] is not identical.
if(endsWith(decodeURIComponent(pair[0]), '[]') ) {
var arrName = decodeURIComponent(pair[0]).substring(0, decodeURIComponent(pair[0]).length - 2);
if(!(arrName in arr)) {
arr.push(arrName);
arr[arrName] = [];
}
arr[arrName].push(decodeURIComponent(pair[1]));
request[arrName] = arr[arrName];
} else {
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
}
return request;
}
where endWith is taken from here
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
/**
* (C)VIOLONIX inc.
* Parser for make multidim array from
* foo[]=any&foo[]=boy, or foo[0][kids]=any&foo[1][kids]=boy
* result: foo=[[any],[boy]] or foo=[kids:[any],kids:[boy]]
*/
var URLToArray = function(url){
function parse_mdim(name, val, data){
let params = name.match(/(\[\])|(\[.+?\])/g);
if(!params)params = new Array();
let tg_id = name.split('[')[0];
if(!(tg_id in data)) data[tg_id] = [];
var prev_data = data[tg_id];
for(var i=0;i<params.length;i++){
if(params[i]!='[]'){
let tparam = params[i].match(/\[(.+)\]/i)[1];
if(!(tparam in prev_data)) prev_data[tparam] = [];
prev_data = prev_data[tparam];
}else{
prev_data.push([]);
prev_data = prev_data[prev_data.length-1];
}
}
prev_data.push(val);
}
var request = {};
var arr = [];
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
if(decodeURIComponent(pair[0]).indexOf('[')!=-1)
parse_mdim(decodeURIComponent(pair[0]), decodeURIComponent(pair[1]), request);
else
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
//To-do here check array and simplifity it: if parameter end with one index in array replace it by value [0]
return request;
}
There's the query-object jQuery plugin for that

Categories