0

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!

1 Answer 1

9

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);
Sign up to request clarification or add additional context in comments.

5 Comments

+1 for deducing exactly what the transform from input to output was without the OP actually saying so.
+1, did'nt see this one, much nicer approach! Also, good eye for catching the base 64.
I've been working with this a lot recently -- it seems to return a string. (found this out through typeof). Is there a way for this to be an object?
Got this through $.parseJSON(string) for anyone whose wondering! Thank you again for your help!
I thought you wanted a JSON string, by the output you gave (you didn't specify a type). Rather than converting to a string then back to an Object / Array, you could just skip the two steps that effectively cancel eachother out - i.e. change JSON.stringify( /* code */, 0, 4) to /* code */ and you'll have the Array without converting to JSON; then you don't need to use parseJSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.