How to loop through & add pairs of values to JSON object?
You are making a lot of confusion between arrays and objects i think. You could do:
var jsonObj = {};
for(var i=0; i<data.length; i++){
jsonObj[data[i].id] = data[i].name;
}
in this way you would have an object that has as properties the "id" contained in "data" and as values of those properties the relative names
Joe W
Updated on August 31, 2020Comments
-
Joe W over 3 years
Using the jQuery SelectBox plugin I'm trying to create a JSON object which looks as follows, where
'value'
and'name'
are pairs of values for a select box:'Opt Group 1': { 'value': 'name', 'value': 'name', 'value': 'name', 'value': 'name', 'value': 'name' },
So that when I loop through my data, I push more data to the end of the array. Currently, to display the
'name'
only, I use the following:var jsonObj = []; for(var i=0; i<data.length; i++){ jsonObj.push(data[i].name); } console.log(jsonObj);
So far as I understand it, JavaScript doesn't seem to like using variables as identifiers, i.e. I can't do:
jsonObj.push({data[i].id:data[i].name});
How might I go about creating the kind of JSON object I need, in order to get the Select Box working as needed?
-
Joe W over 12 yearsWell, you're not wrong that I have a lot of confusion between arrays and objects. Thanks, I'll give this a try.
-
Joe W over 12 yearsSir, you are a gent. That works perfectly. So to confirm, this is just a JSON object? The word array doesn't really count here?
-
Nicola Peluchetti over 12 yearsActually it's not a JSON object, it is a standard javascript Object. There a lot of good articles on Objects and Arrays in Javascript and it's normal to be confused! :)