0

I have a string array like below

'[{"Bangalore": ["blr", "Bengaluru", "bangalore", "BANGALORE", "Bangalore"]}, {"delhi": ["del", "new delhi", "delhi", "nd", "dilli"]}]'

Now I want to loop throug each object and create a new object of my own and store it in a list

This is what I do

json_data = JSON.parse('[{"Bangalore": ["blr", "Bengaluru", "bangalore", "BANGALORE", "Bangalore"]}, {"delhi": ["del", "new delhi", "delhi", "nd", "dilli"]}]')   

tuples_to_return = []
for(i=0;i<json_data.length;i++) {
    for(key in json_data[i]) {
        //console.log(key, json_data[i][key])
        tuples_to_return.push({key: json_data[i][key].join()})
    }
}

console.log(tuples_to_return)

But the weird part is the output comes as

[ { key: 'blr,Bengaluru,bangalore,BANGALORE,Bangalore' },
  { key: 'del,new delhi,delhi,nd,dilli' } ]

Why is the key being printed as the string itself? I was expecting an output like

[ { "Bangalore": 'blr,Bengaluru,bangalore,BANGALORE,Bangalore' },
      { "delhi": 'del,new delhi,delhi,nd,dilli' } ]

When I do a console.log() of the key something like

for(i=0;i<json_data.length;i++) {
        for(key in json_data[i]) {
            console.log(key)
        }
    }

Then it gives me back the key values

Bangalore
delhi

Then what happens when I try to make an object and insert my keys there?

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
Souvik Ray
  • 2,899
  • 5
  • 38
  • 70
  • @gilbert-v — Like what they are doing on line 1 of their code? – Quentin Feb 05 '19 at 11:29
  • 1
    You should not make Array top level in JSON to prevent hijacking: https://haacked.com/archive/2009/06/25/json-hijacking.aspx/ Lead with an Object containing that array :) – DanteTheSmith Feb 05 '19 at 11:31

1 Answers1

0

try this:

json_data = JSON.parse('[{"Bangalore": ["blr", "Bengaluru", "bangalore", "BANGALORE", "Bangalore"]}, {"delhi": ["del", "new delhi", "delhi", "nd", "dilli"]}]')   

tuples_to_return = []
for(i=0;i<json_data.length;i++) {
    for(key in json_data[i]) {
        //console.log(key, json_data[i][key])
        tuples_to_return.push({[key]: json_data[i][key].join()})
    }
}

console.log(tuples_to_return)

if you set {key:'foo'} you get a property name of key. If you set {[key]:'foo'} you get a property name of whatever string key contains.

The response I get from the above code is:

[
  {"Bangalore":"blr,Bengaluru,bangalore,BANGALORE,Bangalore"},
  {"delhi":"del,new delhi,delhi,nd,dilli"}
]
Euan Smith
  • 2,102
  • 1
  • 16
  • 26