Reputation: 979
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!
Upvotes: 0
Views: 104
Reputation: 14924
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);
Upvotes: 5
Reputation: 348
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);
Upvotes: 1
Reputation: 1928
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);
Upvotes: 2
Reputation: 38552
There 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);
Upvotes: 1