简体   繁体   中英

How to convert such example object array to string and revert it back?

I have an object array like this

polyPaths: LatLngLiteral[] = [{lat: 12.994169219614097, lng: 77.62397007054658}
 {lat: 12.984802167360343, lng: 77.67581180638642}
 {lat: 12.957702635784846, lng: 77.65864566869111}
 {lat: 12.974765648082716, lng: 77.61538700169892}];

I want to show this object array as string in textarea

(12.994169219614097,77.62397007054658)
(12.984802167360343,77.67581180638642)
(12.957702635784846,77.65864566869111)
(12.974765648082716,77.61538700169892)

On text input change, I want string revert back to object array of polyPaths .

I tried with following js example:

let stringPath = this.polyPaths.map(path => {
    return '(' + path.lat + ',' + path.lng + ')';
});
var convertedPath = stringPath.join('');
this.polyControls.area.setValue(convertedPath);

But not able to revert it back on input change.

Try the following, it's basic string/array manipulation

 const polyPaths = [{ lat: 12.994169219614097, lng: 77.62397007054658 }, { lat: 12.984802167360343, lng: 77.67581180638642 }, { lat: 12.957702635784846, lng: 77.65864566869111 }, { lat: 12.974765648082716, lng: 77.61538700169892 }] // converting it to a string const convertedPath = polyPaths.map(path => `(${path.lat},${path.lng})`).join('\n'); console.log(convertedPath) // reversing it back const reversed = convertedPath.split('\n').map(x => { const [lat, lng] = x.slice(1, x.length - 1).split(",").map(Number) return { lat, lng } }) console.log(reversed)

Try like below. Explanation is in comments.

 let polyPaths = [{ lat: 12.994169219614097, lng: 77.62397007054658 }, { lat: 12.984802167360343, lng: 77.67581180638642 }, { lat: 12.957702635784846, lng: 77.65864566869111 }, { lat: 12.974765648082716, lng: 77.61538700169892 }]; let stringPath = polyPaths.map(path => { return '(' + path.lat + ',' + path.lng + ')'; }); var convertedPath = stringPath.join(''); console.log(convertedPath); // split your string with ( polyPaths = convertedPath.split('(').filter(path => path.includes(')')) // remove first entry which will be empty string.map(path => ({ lat: path.split(',')[0].trim(), // get lat from each record lng: path.split(',')[1].replace(')', '').trim(), // get lng from each record, remove ) })); console.log(polyPaths);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM