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..
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With