String to Object literal - javascript

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

Related

Reverse whole string while keeping the spaces at the same position

This is the code I have tried. If we input "We are farmers!" it should return "!s rem raferaeW" however the code I have returns "!s remr aferaeW"
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
for (var i = spaces.length - 1; i >=0; i = i - 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
First I pushed each letter of the input into an array at "array1". Then I made an array for the indexes of the spaces of "array1" called "spaces."
Then "array2" is an array of "array1" reversed.
Then "spaces2" is an array of the indexes for "array2" and then I used a for loop to splice out the spaces in array2. Then "nWord" is "array2" combined to form a new word.
Then "array3" is an array for all of nWord's letters and I used a reverse for loop for try to input spaces into "array3" and using the indexes of the "spaces" array. Unfortunately, it is not returning "!s rem raferaeW" and IS returning "!s remr aferaeW".
I am trying to know how I can use the indexes of the "spaces" array to create spaces in "array3" at indexes 2 and 7.
You just need to make following change
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
You are reading spaces array in reverse but as the problem stated spaces should be at same place. Reading it from start to finish fixed the issue.
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
Here is my best crack at it.
const reverseStr = (input) => {
const revArr = input.replaceAll(' ', '').split('').reverse();
for (let i = 0; i < revArr.length; i++) {
if (input[i] === ' ') revArr.splice(i, 0, ' ');
}
return revArr.join('');
}
let words="Today Is A Good Day";
let splitWords=words.split(' ')
console.log(splitWords)
let r=[]
let ulta=splitWords.map((val,ind,arr)=>{
// console.log(val.split('').reverse().join(''))
return r.push(val.split('').reverse().join(''))
})
console.log(r.join(' '))

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

Adding an array of values

This is the json data I have
{
"data" :
{
"Count" : ["1","2","3","4", "5"]
}
}
How can I use jQuery to get the result as
"Result" : ["1", "3","6","10", "15"]
var myArray = [];
var data = myArray.data
for ( var i = 0; i < data.length; i = i + 1 ) {
val = i == 0 ? 0 : myArray[i-1]
myArray.push(data[i]+val)
}
console.log(myArray)
Unless the data is part of an DOM object, I don't see the point of using jQuery.
var myData =
{
"data" :
{
"Count" : ["1","2","3","4", "5"]
}
}
var countAry = myData.data.Count;
var results = new Array(countAry.length);
for (var i = 0, il = countAry.length; i < il; i++) {
results[i] = Number(countAry[i]) + (results[i - 1] || 0);
}
myData.data.Results = results;
console.log(myData);
No need for jQuery, a primitive loop will do that:
// Either
var obj = {"data":{"Count":["1","2","3","4","5"]}}
// or
var obj = JSON.parse(jsonString);
var arr = obj.data.Count,
res = [],
acc = 0;
for (var i=0; i<arr.length; i++)
res[i] = String(acc += Number(arr[i]));
obj.data.Result = res;
Or, if you only want to add the counts to their previous (single) one only, use
for (var i=0; i<arr.length; i++)
res[i] = String(+arr[i] + (i && +arr[i-1]));
If you can use the ECMAScript 5 Array methods: Assuming json is your json data...
var sum = 0,
count = JSON.parse(json).data.Count.map(function(i) {
return parseInt(i, 10) + sum;
});

Convert javascript object of one type into another

I need to convert a JavaScript object of one type:
object1: [{"a":"value1", "b":"value2", "c":"value3"}, {"d":"value4","e":"value5","f":"value6"}]
To another type of object:
object2 : {"value1":["value1", "value2", "value3"], "value4":["value4","value5","value6"]}
I tried to convert it using this function:
function toObject(arr) {
var rv = {};
for (var i = 0; i < arr.length; ++i) {
rv[i] = arr[i];
}
return rv;
}
but I'm getting numerical indexes ([0], [1]) instead of "value1" and "value4". Could you please give me some hint how can I do the conversion from object1 to object2. Thanks.
what you want is to concatenate the vectors inmates?
Try:
function toObject(arr) {
var rv = {}, k;
for (var i = 0; i < arr.length; ++i) {
for(k in arr[i]){
rv[k] = arr[i][k];
}
}
return rv;
}
If this is not what you are looking for then try this:
[Fixed (with the help of user #user1689607)]
[edit]:
Object.keys does not work in older browsers. [Fixed]
function toObject(arr,_sort) {
//param1 = Object, param2 = (true:sort, false:default)
var rv = {}, k, firstV = null, keys, obj, tmp, j,
ObjK = Object.keys ? function(ke){
return Object.keys(ke);
} : function(ke){
var r = [];
for(var o in ke){
r[r.length] = o;
}
return r;
};
for (var i = 0; i < arr.length; ++i) {
obj = arr[i];
tmp = [];
keys = _sort===true ? ObjK(obj).sort() : ObjK(obj);
tmp = [obj[keys[0]]];
for (j = 0; j < keys.length; ++j) {
tmp[tmp.length] = obj[keys[j]];
}
rv[obj[keys[0]]] = tmp;
firstV = null;
}
return rv;
}
//sort
console.log(
toObject([{"a":"value1", "b":"value2", "c":"value3"}, {"d":"value4","e":"value5","f":"value6"}]),
true);
//default
console.log(
toObject([{"a":"value1", "b":"value2", "c":"value3"}, {"d":"value4","e":"value5","f":"value6"}])
);

Spliting based on comma and then space in 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'
}
*/

Categories