Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array to formatted string in javascript [closed]

I have an array element

    [{
    "x": 326,
    "y": 176
}, {
    "x": 244,
    "y": 300
}, {
    "x": 189,
    "y": 420
}, {
    "x": 154,
    "y": 546
}, {
    "x": 139,
    "y": 679
}, {
    "x": 152,
    "y": 827
}, {
    "x": 183,
    "y": 954
}, {
    "x": 230,
    "y": 1088
}, {
    "x": 291,
    "y": 1217
}, {
    "x": 365,
    "y": 1333
}, {
    "x": 446,
    "y": 1417
}, {
    "x": 554,
    "y": 1469
}]

i want to convert this to string like this

"{326,176},{244,300},{189,420},{154,546},{139,679},{152,827},{183,954},  {230,1088},{291,1217},{365,1333},{446,1417},{554,1469}"

How can we achieve this in javascript.. Thanks in advance..

like image 416
Sagar Jagadesh Avatar asked Dec 24 '22 05:12

Sagar Jagadesh


1 Answers

Here's one way to do it, using a combination of Array.prototype.map() and Array.prototype.join():

var ele = '[{"x":326,"y":176},{"x":244,"y":300},{"x":189,"y":420},{"x":154,"y":546},{"x":139,"y":679},{"x":152,"y":827},{"x":183,"y":954},{"x":230,"y":1088},{"x":291,"y":1217},{"x":365,"y":1333},{"x":446,"y":1417},{"x":554,"y":1469}]';

var array = JSON.parse(ele);
var string = array.map(i => '{' + i.x + ',' + i.y + '}').join();

console.log(string);

This outputs:

{326,176},{244,300},{189,420},{154,546},{139,679},{152,827},{183,954},{230,1088},{291,1217},{365,1333},{446,1417},{554,1469}

Update

Using newer language features like object destructuring and template strings, the map() operation can now be rewritten as follows:

var ele = '[{"x":326,"y":176},{"x":244,"y":300},{"x":189,"y":420},{"x":154,"y":546},{"x":139,"y":679},{"x":152,"y":827},{"x":183,"y":954},{"x":230,"y":1088},{"x":291,"y":1217},{"x":365,"y":1333},{"x":446,"y":1417},{"x":554,"y":1469}]';

var array = JSON.parse(ele);
var string = array.map(({x, y}) => `{${x},${y}}`).join();

console.log(string);
like image 133
Robby Cornelissen Avatar answered Dec 26 '22 19:12

Robby Cornelissen