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.
-
2Technically, 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– Mike Cluck2016年02月02日 23:46:34 +00:00Commented Feb 2, 2016 at 23:46
-
1stackoverflow.com/questions/10773564/… is probably worth readingQuentin– Quentin2016年02月02日 23:51:24 +00:00Commented Feb 2, 2016 at 23:51
-
1Besides the single versus double quote issue, you need commas in between each of the child arrays.nnnnnn– nnnnnn2016年02月02日 23:56:06 +00:00Commented Feb 2, 2016 at 23:56
1 Answer 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.
2 Comments
forEach doesn't set this to the current element. You'd need to accept a parameter and use that parameter instead.