I hava a string like this "sum 123,645,423,123,432";
How can i convert this string to be like this:
{
"sum": [ 123,645,423,123,432 ]
}
I try it like this:
var arr = "sum 123,645,423,123,432";
var c = arr.split(',');
console.log(c);
VM3060:1 (5) ["sum 123", "645", "423", "123", "432"]
Thanks!
-
3What did you try to convert it like that?A l w a y s S u n n y– A l w a y s S u n n y2020年06月15日 09:08:25 +00:00Commented Jun 15, 2020 at 9:08
-
1Please read idownvotedbecau.se/noattemptFZs– FZs2020年06月15日 09:10:34 +00:00Commented Jun 15, 2020 at 9:10
-
Posted an answer below based on your try, hope it will help you somehowA l w a y s S u n n y– A l w a y s S u n n y2020年06月15日 09:25:09 +00:00Commented Jun 15, 2020 at 9:25
4 Answers 4
First, i .split() the string by whitespace, that returns me an array like this ["sum" , "123,645,423,123,432"]
Instead of writing var name = str.split(" ")[0] and var arrString = str.split(" ")[1] i used an destructuring assignment
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Next step is to split the arrString up by , and then .map() over each element and convert it to an number with Number().
Finally i assign an object to result with a dynamic key [name] and set arr to the dynamic property.
var str = "sum 123,645,423,123,432";
var [name,arrString] = str.split(" ");
var arr = arrString.split(",").map(Number);
let result = {
[name]: arr
}
console.log(result);
//reverse
var [keyname] = Object.keys(result);
var strngArr = arr.join(",");
var str = `${keyname} ${strngArr}`
console.log(str);
7 Comments
var result = arr.join(",")const str = "sum 123,645,423,123,432";
const splittedString = str.split(" ");
const key = splittedString[0];
const values = splittedString[1].split(",").map(Number);
const myObject = {
[key]: [...values]
};
console.log(myObject);
3 Comments
Uncaught SyntaxError: Missing initializer in const declarationThere are many ways to dot that,one way to do it using String.prototype.split()
let str = "sum 123,645,423,123,432";
let split_str = str.split(' ');
let expected = {};
expected[split_str[0]] = split_str[1].split(',');
console.log(expected);
2 Comments
This solution is equivalent to @Yohan Dahmani with the use of destructuring array for more legible code.
const str = "sum 123,645,423,123,432";
const [key,numbersStr] = str.split(' ');
const numbersArr = numbersStr.split(',').map(n => parseInt(n, 10));
const result = {[key]: numbersArr};
console.log(result);
1 Comment
[key] means indeed.