0

I am trying to take a JSON list that is formatted as such: (real list has over 2500 entries).

  [
     ['fb.com', 'http://facebook.com/']
     ['ggle.com', 'http://google.com/']
  ]

The JSON list represents: ['request url', 'destination url']. It is for a redirect audit tool built on node.js.

The goal is to put those JSON value pairs in a javascript object with a key value array pair as such:

    var importedUrls = {
            requestUrl : [
                             'fb.com',
                             'ggle.com'
                         ],
        destinationUrl : [
                             'https://www.facebook.com/',
                             'http://www.google.com/' 
                         ]
    }

Due to the sheer amount of redirects, I do prefer a nonblocking solution if possible.

Jamesc892
  • 15
  • 5
  • 2
    Technically, that isn't valid JSON because JSON requires double-quotes, not single quotes. But those are valid Javascript arrays. As for your question: what have you tried? – Mike Cluck Feb 02 '16 at 23:46
  • 1
    http://stackoverflow.com/questions/10773564/which-would-be-better-for-concurrent-tasks-on-node-js-fibers-web-workers-or-t is probably worth reading – Quentin Feb 02 '16 at 23:51
  • 1
    Besides the single versus double quote issue, you need commas in between each of the child arrays. – nnnnnn Feb 02 '16 at 23:56

1 Answers1

1

You first need to create your object:

var importedUrls = {
  requestUrl: [],
  destinationUrl: []
}

Now, let's say you have your data in an array called importedData for lack of a better name. You can then iterate that array and push each value to its proper new array:

importedData.forEach(function(urls){
  importedUrls.requestUrl.push(urls[0]);
  importedUrls.destinationUrl.push(urls[1]);
});

This will format your object as you want it to be formatted, I hope.

I will propose it to you that you take another approach. Why not have an array of importedUrls, each one with its correspondent keys?

You could have something like:

importedUrls = [
  {
     requestUrl: 'req',
     destinationUrl: 'dest'
  },
  {
     requestUrl: 'req2',
     destinationUrl: 'dest2'
  },
]

I'm sure you can figure out how to tweak the code I showed to fit this format if you want to. What you gain with this is a very clear separation of your urls and it makes the iterations a lot more intuitive.

Jonas Meinerz
  • 612
  • 3
  • 9
  • 1
    [`forEach` doesn't set `this` to the current element](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). You'd need to accept a parameter and use that parameter instead. – Mike Cluck Feb 02 '16 at 23:54
  • This answered my question - and helped me better understand object arrays. I did end up implementing the arrays with each object having corresponding keys - it was a better method of combing through everything. I appreciate the help! – Jamesc892 Feb 08 '16 at 15:48