Construct JSON object from array on client-side?

Construct JSON object from array on client-side?

Problem

I have a string array like this:

['QWJvdXQ=','SG93IGl0IFdvcmtz','SG9tZQ==','Q29udHJpYnV0ZQ==','Q29udGFjdA==']

What I want to do, is turn it into something like this:

[
   {
       "id" : "QWJvdXQ=",
       "url": "about.html"

   },
   {
       "id" : "SG93IGl0IFdvcmtz",
       "url": "how_it_works.html"

   },
   {
       "id" : "SG9tZQ==",
       "url": "index.html"

   },
   {

       "id" : "Q29udHJpYnV0ZQ==",
       "url": "contribute.html"
   },
   {
       "id" : "Q29udGFjdA=="
       "url": "contact.html"
   }
]

The attributes aren’t the focus — what I’m basically trying to do is make each item in the array an object with the value as an value of an attribute, and add another (or more) key-value pairs into those objects.

Right now, I’m trying to do this on the client-side, using jQuery and JS. I also am running node.js, so if this is easier to do on the server-side I’m open to any suggestions. Any help is appreciated!

Problem courtesy of: streetlight

Solution

What you need

all together;

JSON.stringify(
    ['QWJvdXQ=','SG93IGl0IFdvcmtz','SG9tZQ==','Q29udHJpYnV0ZQ==','Q29udGFjdA=='].map(
        function (e) {
            return {
                    'id': e,
                    'url': atob(e).toLowerCase().replace(/\s/g, '_') + '.html'
                   }; // I converted the string to URL as I expect you wanted
        }
    ),
0, 4);
Solution courtesy of: Paul S.

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *