I want to cycle through an array of strings and split those strings on a certain character, and then feed those new strings into an array, ex. take the string "val: key" from the first array and then use a function to retrieve the string from the array and split it on ":" into a new array that would contain ["val","key"]. This is what I have so far, and at the bottom is what is returning when console.log it.
var dict = [];
dict.push("me; pro: myself");
dict.push("labor, laboris; n: work");
dict.push("voco, vocare, vocavi, vocatum; v: call");
function parseDict(arr){
/* parseDict takes a dictionary entry and splits it between its latin part and its part of speech/english translation*/
var dictFinal = [];
arr.toString();
for (i = 0; i < arr.length; i++){
dictFinal[i] += arr[i].split(";");
}
return dictFinal;
}
console.log(parseDict(dict)) prints out
[ 0: "undefinedme; pro: myself"
1: "undefinedlabor, laboris; n: work"
2: "undefinedvoco, vocare, vocavi, vocatum; v: call"
]
Why is it not splitting into two strings on the ";", and why is it returning an undefined value?
It is undefined because you are doing += to an empty array index
dictFinal[i] += arr[i].split(";");
^^
First pass dictFinal[i] is undefined so it is
dictFinal[i] = undefined + arr[i].split(";");
You probably just want
dictFinal[i] = arr[i].split(";");
Use dictFinal.push(...) or dictFinal[i] = ...
Calling arr.toString(); doesn't do much in your case; it simply makes a string from the array which is then expected to be assigned to an variable / returned etc...
var dict = [];
dict.push("me; pro: myself");
dict.push("labor, laboris; n: work");
dict.push("voco, vocare, vocavi, vocatum; v: call");
function parseDict(dict) {
// considered that you know the final length of the final
// length of the array you could use: new Array(dict.length)
var dictFinal = [];
for (i = 0; i < dict.length; i++) {
dictFinal[i] = dict[i].split(";");
}
return dictFinal;
}
console.log(parseDict(dict)); // [["me"," pro: myself"],["labor, laboris"," n: work"],["voco, vocare, vocavi, vocatum"," v: call"]]
+= will try to get whatever is in the variable and concat / add with whatever is on the right side of the equal sign:
var a = 'abc';
a += 'def';
console.log(a); // abcdef
var b = 1;
b += 1;
console.log(b); // 2
// and your's case:
var c; // here c === undefined (your case dictFinal[i] === undefined)
c += 'ABC';
console.log(c); // undefinedABC
var my_array = [1,2,3];
// .toString() is called on the array so the concatenation can happen:
// It would be the same as writing:
// 'my_string' + my_array.toString();
// or 'my_string' + my_array.join(',');
var d = 'my_string' + my_array;
console.log(d); // my_string1,2,3
if you really need the += and would not want to see the 'UNDEFINED', could try:
dictFinal[i] = ((typeof dictFinal[i]!=='undefined') ? dictFinal[i]+arr[i].split(";") : arr[i].split(";"));
Related
I am new to javascript still trying to learn things.
I've found a solution to a problem about a function that should generate all combinations of a characters within a string.
I'm trying to figure out:
What is happening inside the loop?
How does the loops execute step by step?
I cannot figure how it reaches to that final output.
I tried for a long time to figure out but I m not sure what happens inside those
loops. I don't understand tho how it gets "ab", "ac". ... together
in the final output and where arrTemp pushes result[x] and char. I saw that the result array is initially empty, then is concatenated with arrTemp.
Here is the code I'm struggling with:
function combString(str){
var lenStr = str.length;
var result = [];
var indexCurrent = 0;
while(indexCurrent < lenStr){
var char = str.charAt(indexCurrent);
var x;
var arrTemp = [char];
for(x in result) {
arrTemp.push(""+result[x]+char);
}
result = result.concat(arrTemp);
indexCurrent++;
}
return result;
}
console.log(combString("abc"));
And this is the output
["a", "b", "ab", "c", "ac", "bc", "abc"]
We can simply achieve it by using 'Slice'
function combinator (s) {
list_of_strings = new Array();
for(i=0;i<s.length;i++) {
for(j=i+1;j<s.length+1;j++) {
list_of_strings.push(s.slice(i, j));
}
}
return list_of_strings;
}
document.write(combinator("dog"));
ok that's pretty simple frist I will comment the code for you and then I will show what is done with a simple string example:
function combString(str){
var lenStr = str.length;
var result = [];
var indexCurrent = 0;
while(indexCurrent < lenStr){ // repeat until indexCurrent equals lenStr, the aim is to browse threw the string
var char = str.charAt(indexCurrent); // select the char at indexCurrent
var x;
var arrTemp = [char];//put the selected char in an array
for(x in result) {
/*Here it's a little bit tricky, array are object, and actually
the indexes of the array are properties which names are includes between 0 and
2³²-2, but they can have other properties like any other object. that's
the reason why you can use a for in loop here which will go threw the
array and perform action on its properties with property name stored in the x variable (actually it is better to use a foreach loop) */
arrTemp.push(""+result[x]+char); /* so here you concat the
value of the current property of result (in the for in loop) with the char
at indexCurrent and you add the concatenation result at the end of arrTemp */
}
result = result.concat(arrTemp); //here you concat result array and arrTemp and assign the concatenation result to result (I know there is a lot of result ahah)
indexCurrent++; //and then you go to the next char in the string and you repeat
}
// when the while loop ends you return result
return result;
}
so let's see an example with this string "abc":
for indexCurrent =0 :
result = [];
char = 'a';
arrayTemp (before for in loop)= ['a'];
arrayTemp (after for in loop)= ['a'];
result = ['a'];
for indexCurrent =1 :
result = ['a'];
char = 'b';
arrayTemp (before for in loop) = ['b'];
arrayTemp (after for in loop) = ['b','ab']
result = ['a', 'b', 'ab'];
for indexCurrent =2 :
result = ['a', 'b', 'ab'];
char = 'c';
arrayTemp (before for in loop) = ['c'];
arrayTemp (after for in loop) = ['c','ac','bc','abc']
result = ['a', 'b', 'ab','c','ac','bc','abc'];
I hope that helped you
Here is the commented code, hopefully it will help you understand!
function combString(str) {
//String length
var lenStr = str.length;
//Initially empty, where the results will be stored
var result = [];
//Currently selected letter
var indexCurrent = 0;
//Looping from 0 to the length of the string
//var char is selecting the character at this index. Ex: "a", then "b", then "c"
while (indexCurrent < lenStr) {
//Get the character at the index position.
var char = str.charAt(indexCurrent);
var x;
var arrTemp = [char];
//For each previous result
for (x in result) {
//Add the current character to the index
arrTemp.push("" + result[x] + char);
/*
* Ex: "abc"
* First round: result is empty, so this code doesn't execute
* Second round: result contains "a". Adds "ab" to the result array
* - Then. result array will contain "a","b" and "ab"
* Third round: result contains "a","b","ab"
* For all of these results, add "c" to the resulting array
* Ex: "ac","bc", "abc"
* - Then add "c"
*/
}
result = result.concat(arrTemp);
//Increment the current index to go to the next character
indexCurrent++;
}
return result;
}
console.log(combString("abc"));
Let's assume input is "ab". Here's how the function works without the loops:
var str = "ab";
var lenStr = str.length;
var result = [];
var indexCurrent = 0;
var char, x, arrTemp;
//first while iteration begins
//indexCurrent === 0
//so char becomes "a"
char = str.charAt(indexCurrent);
//A temp array is created so it can be concatenated to the results array.
arrTemp = [char];
//arrTemp == ["a"]
//for-loop here, but since the result array is empty, it wont execute
//result becomes ["a"]
result = result.concat(arrTemp);
//indexCurrent becomes 1
indexCurrent++;
//second while iteration begins
//indexCurrent === 1
//so char becomes "b"
char = str.charAt(indexCurrent);
arrTemp = [char];
//arrTemp == ["b"]
//For-loop begins, x === 0
//result[x] is the xth (in this case, first) value of the result-array
//the double quotes cast the result as string
//in other words, it says:
//"store at the end of the array arrTemp, as string, the value from index x
//in the array result, plus the character stored in the variable char"
arrTemp.push(""+result[x]+char);
//arrTemp is now ["b", "ab"]
//result only has one item, so for-loop ends
//result becomes ["a", "b", "ab"]
result = result.concat(arrTemp);
//indexCurrent becomes 2
indexCurrent++;
//function returns result
Do note that for-in loops should not be used for iterating over arrays (see here).
Simple use of for loop and while statement to get different combinations.
function combu(s){
var buff = [];
var res = [];
for (i=0;i<s.length;i++){
buff = [s[i]];
var index=0;
while(res[index]){
buff.push(''+res[index]+s[i]);
index++;
}
res = res.concat(buff);
}
return res;
}
combu('abc');
Suppose I create a function that flips an array's elements. For example, the function takes in [1,2,3,4] and flips it to [4,3,2,1]. My function is capable of doing that. However, I want to do something that doesn't seem to work. If I call the function like this: flip("hello"), I want it to change "hello" to an array like this: [h,e,l,l,o], flip the elements to become like this: o,l,l,e,h then join the elements together to make it olleh. This is what I have been able to make so far:
function reverse (A) {
if(typeof(A) == 'string') { A.toString().split(" "); }
var i1 = 0;
var i2 = A.length - 1;
function swap(A, i1, i2) {
var temp = A[i1];
A[i1] = A[i2];
A[i2] = temp;
return A;
}
var index1 = 0;
var index2 = A.length - 1;
var temp = A[index1];
for(let i = index1; i < index2; i++) {
swap(A, i, index2); index2--;
}
console.log(A);
}
This does not work at all. I think that is because I am not dealing with what is being called but rather the parameter itself. I have also tried:
if(typeof(reverse(A)) == 'string') {A.toString().split(" "); }
However, that gives me a result that says: RangeError: Maximum call stack size exceeded
I have been searching for an hour with no success. Any help?
Replace
A.toString().split(" ");
with
A = A.split(""); // empty string for splitting, splits every character
because you need an assignment and while A is already an string, you do not need toString().
Later you have to return the joined array with:
return A.join('');
Methods used:
String.prototype.split()
The split() method splits a String object into an array of strings by separating the string into substrings.
Array.prototype.join()
The join() method joins all elements of an array into a string.
Complete working code with some minor changes:
function reverse(a) {
function swap(b, i1, i2) {
var temp = b[i1];
b[i1] = b[i2];
b[i2] = temp;
}
var index1 = 0,
index2 = a.length - 1,
isString = typeof a === 'string';
if (isString) {
a = a.split("");
}
for (index1 = 0; index1 < index2; index1++) {
swap(a, index1, index2);
index2--;
}
return isString ? a.join('') : a;
}
document.write('<pre>' + JSON.stringify(reverse([100, 101, 102]), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(reverse('hello'), 0, 4) + '</pre>');
<pre><code>
<script>
function myFunction() {
var str = "hello";
var splitting = str.split("");
var reversed_array=splitting.reverse();
var result=reversed_array.join("");
document.getElementById("demo").innerHTML = result;
}
</script>
</code></pre>
Function that are used
split :- which will split the string into array .
reverse :- which will be used to reverse the array .
join :- It will join the reversed array
javascript stringarrayfunction
I have an array and I want to remove all the string elements from it.
This is what I have so far. The result is not what I want since it returns only "bicycle"
Also, I am doing this in Test Complete so I need to have a main function that logs the result.
function ex06(){
var mailBox = "mailbox";
var twenty = 20;
var isItRaining = true;
var goat = "";
var stringsArray = ["bicycle", "pocket", 3, mailBox, twenty, isItRaining, goat];
var result = removeStrings();
Log.Message("stringsArray looks like this after the removal of all the string elements: " + result);
function removeStrings(){
var i;
var x
for(i = 0; i < stringsArray.length; i++){
if (typeof(stringsArray[i]) === 'string'){
x = stringsArray.splice(i, 1);
return x;
}
}
}
}
Version 1, with Array#filter
var a = [1, 2, "3", "4", true];
a = a.filter(function (e) {
return typeof e !== 'string';
});
document.write('<pre>' + JSON.stringify(a, 0, 4) + '</pre>');
Version 2, with Array#splice and running backwards.
var a = [1, 2, "3", "4", true],
i = a.length;
while (i--) {
if (typeof a[i] === 'string') {
a.splice(i, 1);
}
}
document.write('<pre>' + JSON.stringify(a, 0, 4) + '</pre>');
The Array.prototype.filter method is what you need:
var stringsArray = ["bicycle", "pocket", 3, mailBox, twenty, isItRaining, goat];
var result = stringsArray.filter(function(element) {
return typeof element !== 'string';
});
you need to reduce the counter variable and check the original array
try this simple example
var a = [1,2,"3", "4", true];
for( var counter = 0; counter < a.length; counter++)
{
if ( (typeof a[ counter ] ) == "string" )
{
a.splice(counter,1); counter--;
}
}
console.log(a); //output [1, 2, true]
try this code:
function ex06(){
var mailBox = "mailbox";
var twenty = 20;
var isItRaining = true;
var goat = "";
var stringsArray = ["bicycle", "pocket", 3, mailBox, twenty, isItRaining, goat];
var result = removeStrings();
Log.Message("stringsArray looks like this after the removal of all the string elements: " + result);
function removeStrings(){
var newarray = [];
var i;
var x
for(i = 0; i < stringsArray.length; i++){
if (typeof(stringsArray[i]) !== 'string'){
newarray.push(stringsArray[i]);
}
}
return newarray
}
}
JavaScript offers native methods to filter arrays, so that you can remove string elements more easily: Array.prototype.filter can make the process a lot easier (and prevents strange behaviours when using splice inside a loop).
function ex06(){
var mailBox = "mailbox";
var twenty = 20;
var isItRaining = true;
var goat = "";
var stringsArray = ["bicycle", "pocket", 3, mailBox, twenty, isItRaining, goat];
var result = removeStrings(stringsArray);
Log.Message("stringsArray looks like this after the removal of all the string elements: " + result);
function removeStrings(arrayWithString){
return arrayWithString.filter(function(item) {
return typeof item !== 'string'; // returns only items which are not strings
});
}
}
A small piece of advice: Pass in the array into your function instead of referencing it from the parent scope. This way you have a pure, reusable function (and no strange side effects you might not want).
I assume this is an exercise, and that's why you're not using Array#filter.
The problem is that you have your return x inside your for loop, so you return the first string you find.
You have at least three options:
Don't return anything, since removeStrings is modifying the original array. That one's easy: Just remove the return x; line.
Don't modify the original array; instead, create and return a new array with the strings left out. In that case, you'd start with x = [] before the loop, remove the splice call, and instead push any non-string onto x.
Modify the original array, and create and return a new array containing the strings you've removed. In that case, you'd remove return x from inside the loop, have x = [] before the loop, and push the entries you remove onto x. Then return x at the end.
In any of the places where you're modifying the original, note gurvinder372's point that when you remove an entry, you need to not increase the index counter, as you'll end up skipping the next entry.
I wouldn't do it the way he suggests, though; when I'm looping through an array modifying it, for isn't what I reach for, I reach for while:
i = 0;
while (i < stringsArray.length) {
if (typeof stringsArray[i] === 'string'){
stringsArray.splice(i, 1);
// We leave `i` alone here, because we need to process
// the new `stringsArray[i]` on the next pass
} else {
// Didn't remove this entry, move past it
++i;
}
}
Side note: typeof isn't a function, it's an operator, there's no need to put its operand in ():if (typeof stringsArray[i] === 'string'){
I have a js object which looks like this:
var detailsArray = [
{a0 :1,
b0 :'A'},
{a1 :2,
b1 :'B'},
{a2 :3,
b2 :'C'},
{a3 :4,
b3 :'D'}];
This is how the object is created from the server side. On the client side I want to retrieve the value of all 'a's and add them to an array. The problem is that the variable name is changing depending on the index number. I have tried using underscore.js to do something like this:
var variableA = new Array();
for(var i = 0;i<detailsArray.length;i++){
var temp = 'a' + i;
variableA[i] = _.pluck(detailsArray,temp);
}
But this does not work. Can anyone tell how to get the values??
There is two ways for accessing properties of object in javascript : using the dot like you just done, or using the array syntax style.
var obj = {'a':5};
obj.a
obj['a']
So with your code, this would give this :
var variableA = new Array();
for(var i = 0;i<detailsArray.length;i++){
variableA[i] = detailsArray[i]['a' + i];
}
With underscore, you could do:
_.reduce(_.map(detailsArray, function(o, i) {
return o['a' + i];
}), function(a, b) {
return a + b;
});
And with native JS in newer browsers:
detailsArray.map(function(o, i) {
return o['a' + i];
}).reduce(function(a, b) {
return a + b;
});
You can also do it like that:
for (var i = 0; i < detailsArray.length; i++)
alert(eval("detailsArray[" + i + "].a" + i));
The code I provide will alert all the values corresponding to as in the json array, but obviously you can do whatever you want with the values obtained.
Here I am counting that all the keys will be of the kind a smth, but I suppose this is a safe assumption.
here's one possible implementation
var tmp = [];
for (var i = 0; i < detailsArray.length; i++) {
var obj = detailsArray[i]; // current object at index
for (var props in obj) { // iterate properties in current object
if (props.charAt() == "a") { // if starts with a....
tmp.push(obj[props]); // add value to array
break; // stop the property iteration and move to next object
}
}
}
console.log(tmp); // [1,2,3,4]
I have a string as
string = "firstName:name1, lastName:last1";
now I need one object obj such that
obj = {firstName:name1, lastName:last1}
How can I do this in JS?
Actually, the best solution is using JSON:
Documentation
JSON.parse(text[, reviver]);
Examples:
1)
var myobj = JSON.parse('{ "hello":"world" }');
alert(myobj.hello); // 'world'
2)
var myobj = JSON.parse(JSON.stringify({
hello: "world"
});
alert(myobj.hello); // 'world'
3)
Passing a function to JSON
var obj = {
hello: "World",
sayHello: (function() {
console.log("I say Hello!");
}).toString()
};
var myobj = JSON.parse(JSON.stringify(obj));
myobj.sayHello = new Function("return ("+myobj.sayHello+")")();
myobj.sayHello();
Your string looks like a JSON string without the curly braces.
This should work then:
obj = eval('({' + str + '})');
WARNING: this introduces significant security holes such as XSS with untrusted data (data that is entered by the users of your application.)
If I'm understanding correctly:
var properties = string.split(', ');
var obj = {};
properties.forEach(function(property) {
var tup = property.split(':');
obj[tup[0]] = tup[1];
});
I'm assuming that the property name is to the left of the colon and the string value that it takes on is to the right.
Note that Array.forEach is JavaScript 1.6 -- you may want to use a toolkit for maximum compatibility.
This simple way...
var string = "{firstName:'name1', lastName:'last1'}";
eval('var obj='+string);
alert(obj.firstName);
output
name1
Since JSON.parse() method requires the Object keys to be enclosed within quotes for it to work correctly, we would first have to convert the string into a JSON formatted string before calling JSON.parse() method.
var obj = '{ firstName:"John", lastName:"Doe" }';
var jsonStr = obj.replace(/(\w+:)|(\w+ :)/g, function(matchedStr) {
return '"' + matchedStr.substring(0, matchedStr.length - 1) + '":';
});
obj = JSON.parse(jsonStr); //converts to a regular object
console.log(obj.firstName); // expected output: John
console.log(obj.lastName); // expected output: Doe
This would work even if the string has a complex object (like the following) and it would still convert correctly. Just make sure that the string itself is enclosed within single quotes.
var strObj = '{ name:"John Doe", age:33, favorites:{ sports:["hoops", "baseball"], movies:["star wars", "taxi driver"] }}';
var jsonStr = strObj.replace(/(\w+:)|(\w+ :)/g, function(s) {
return '"' + s.substring(0, s.length-1) + '":';
});
var obj = JSON.parse(jsonStr);
console.log(obj.favorites.movies[0]); // expected output: star wars
If you have a string like foo: 1, bar: 2 you can convert it to a valid obj with:
str
.split(',')
.map(x => x.split(':').map(y => y.trim()))
.reduce((a, x) => {
a[x[0]] = x[1];
return a;
}, {});
Thanks to niggler in #javascript for that.
Update with explanations:
const obj = 'foo: 1, bar: 2'
.split(',') // split into ['foo: 1', 'bar: 2']
.map(keyVal => { // go over each keyVal value in that array
return keyVal
.split(':') // split into ['foo', '1'] and on the next loop ['bar', '2']
.map(_ => _.trim()) // loop over each value in each array and make sure it doesn't have trailing whitespace, the _ is irrelavent because i'm too lazy to think of a good var name for this
})
.reduce((accumulator, currentValue) => { // reduce() takes a func and a beginning object, we're making a fresh object
accumulator[currentValue[0]] = currentValue[1]
// accumulator starts at the beginning obj, in our case {}, and "accumulates" values to it
// since reduce() works like map() in the sense it iterates over an array, and it can be chained upon things like map(),
// first time through it would say "okay accumulator, accumulate currentValue[0] (which is 'foo') = currentValue[1] (which is '1')
// so first time reduce runs, it starts with empty object {} and assigns {foo: '1'} to it
// second time through, it "accumulates" {bar: '2'} to it. so now we have {foo: '1', bar: '2'}
return accumulator
}, {}) // when there are no more things in the array to iterate over, it returns the accumulated stuff
console.log(obj)
Confusing MDN docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Demo: http://jsbin.com/hiduhijevu/edit?js,console
Function:
const str2obj = str => {
return str
.split(',')
.map(keyVal => {
return keyVal
.split(':')
.map(_ => _.trim())
})
.reduce((accumulator, currentValue) => {
accumulator[currentValue[0]] = currentValue[1]
return accumulator
}, {})
}
console.log(str2obj('foo: 1, bar: 2')) // see? works!
You need use JSON.parse() for convert String into a Object:
var obj = JSON.parse('{ "firstName":"name1", "lastName": "last1" }');
if you're using JQuery:
var obj = jQuery.parseJSON('{"path":"/img/filename.jpg"}');
console.log(obj.path); // will print /img/filename.jpg
REMEMBER: eval is evil! :D
I implemented a solution in a few lines of code which works quite reliably.
Having an HTML element like this where I want to pass custom options:
<div class="my-element"
data-options="background-color: #dadada; custom-key: custom-value;">
</div>
a function parses the custom options and return an object to use that somewhere:
function readCustomOptions($elem){
var i, len, option, options, optionsObject = {};
options = $elem.data('options');
options = (options || '').replace(/\s/g,'').split(';');
for (i = 0, len = options.length - 1; i < len; i++){
option = options[i].split(':');
optionsObject[option[0]] = option[1];
}
return optionsObject;
}
console.log(readCustomOptions($('.my-element')));
In your case, The short and beautiful code
Object.fromEntries(str.split(',').map(i => i.split(':')));
I'm using JSON5, and it's works pretty well.
The good part is it contains no eval and no new Function, very safe to use.
string = "firstName:name1, lastName:last1";
This will work:
var fields = string.split(', '),
fieldObject = {};
if( typeof fields === 'object') ){
fields.each(function(field) {
var c = property.split(':');
fieldObject[c[0]] = c[1];
});
}
However it's not efficient. What happens when you have something like this:
string = "firstName:name1, lastName:last1, profileUrl:http://localhost/site/profile/1";
split() will split 'http'. So i suggest you use a special delimiter like pipe
string = "firstName|name1, lastName|last1";
var fields = string.split(', '),
fieldObject = {};
if( typeof fields === 'object') ){
fields.each(function(field) {
var c = property.split('|');
fieldObject[c[0]] = c[1];
});
}
const text = '{"name":"John", "age":30, "city":"New York"}';
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr.name;
This is universal code , no matter how your input is long but in same schema if there is : separator :)
var string = "firstName:name1, lastName:last1";
var pass = string.replace(',',':');
var arr = pass.split(':');
var empty = {};
arr.forEach(function(el,i){
var b = i + 1, c = b/2, e = c.toString();
if(e.indexOf('.') != -1 ) {
empty[el] = arr[i+1];
}
});
console.log(empty)
Here is my approach to handle some edge cases like having whitespaces and other primitive types as values
const str = " c:234 , d:sdfg ,e: true, f:null, g: undefined, h:name ";
const strToObj = str
.trim()
.split(",")
.reduce((acc, item) => {
const [key, val = ""] = item.trim().split(":");
let newVal = val.trim();
if (newVal == "null") {
newVal = null;
} else if (newVal == "undefined") {
newVal = void 0;
} else if (!Number.isNaN(Number(newVal))) {
newVal = Number(newVal);
}else if (newVal == "true" || newVal == "false") {
newVal = Boolean(newVal);
}
return { ...acc, [key.trim()]: newVal };
}, {});
In your case
var KeyVal = string.split(", ");
var obj = {};
var i;
for (i in KeyVal) {
KeyVal[i] = KeyVal[i].split(":");
obj[eval(KeyVal[i][0])] = eval(KeyVal[i][1]);
}
var stringExample = "firstName:name1, lastName:last1 | firstName:name2, lastName:last2";
var initial_arr_objects = stringExample.split("|");
var objects =[];
initial_arr_objects.map((e) => {
var string = e;
var fields = string.split(','),fieldObject = {};
if( typeof fields === 'object') {
fields.forEach(function(field) {
var c = field.split(':');
fieldObject[c[0]] = c[1]; //use parseInt if integer wanted
});
}
console.log(fieldObject)
objects.push(fieldObject);
});
"objects" array will have all the objects
I know this is an old post but didn't see the correct answer for the question.
var jsonStrig = '{';
var items = string.split(',');
for (var i = 0; i < items.length; i++) {
var current = items[i].split(':');
jsonStrig += '"' + current[0] + '":"' + current[1] + '",';
}
jsonStrig = jsonStrig.substr(0, jsonStrig.length - 1);
jsonStrig += '}';
var obj = JSON.parse(jsonStrig);
console.log(obj.firstName, obj.lastName);
Now you can use obj.firstName and obj.lastName to get the values as you could do normally with an object.
You don't have to always convert to JSON
So here "person begin as a string!" Finally, "person is converted to object", no necessarily to JSON.
function strToObj(e){if(typeof e=="string"){ let obj=new Function("return" +e); try{return obj()}catch{console.log("Fix, String no allowed to object")}}else{console.log("it is not a string") } };
//Example, person is a string
let person='{firstName:"John", lastName:"Doe", id: 55, fullName:function(){return this.firstName+" "+this.lastName} }';
console.log(strToObj(person));
And it run functions internal to the object without major issues if it is called:
person=strToObj(person); console.log(person.fullName())
Simply, string = "firstName:name1, lastName:last1";
let string = "firstName:name1, lastName:last1";
let object= strToObj("{"+string+"}");
console.log(object)