-1

I have a question on how to build an object structure in java script. I would like to have an object built in the following format:

select1Data = {
"some_email1@gmail.com" : "fname1 lname1",
"some_email2@gmail.com" : "fname2 lname2",
"some_email3@gmail.com" : "fname3 lname3"
};

The code I use is as follows:

$.ajax({
    method: "POST",
    url: "php/somescript.php",
    data: {"email": "some_email@gmail.com"},
}).done(function( data ) {
        var result = $.parseJSON(data);
        let select1Data = { null: null };
        if (result!== null){
                var len = result.length;
                for(var i=0; i<len; i++){
                        userName = result[i].imie + " " + result[i].nazwisko;
                        eMail = result[i].email;
                        let selectNewData = {eMail : userName};
                        Object.assign(select1Data, selectNewData);
                };
        
            }
        });

but this does not work. How can I append or build in another way this object?

bzc0fq
  • 579
  • 1
  • 3
  • 18
  • 1
    _"but this does not work"_ - Please explain what doesn't work. Are you getting an error, are you seeing `eMail` instead of it's value, is your object not updating (if so, how are you checking your object), ... what is the actual issue? – Nick Parsons Nov 27 '22 at 22:42
  • I get first object line empty then only one new line including last record from ajax call – bzc0fq Nov 27 '22 at 22:46
  • Ajax returns 5 rows which is as expected but I can see only one (the last one) in the object structure – bzc0fq Nov 27 '22 at 22:48

1 Answers1

1

the line

let selectNewData = {eMail : userName};

will not do what you hope it do and is equivalent to {"eMail": userName}.

try:

let selectNewData = {};
selectNewData[eMail] = userName;
IT goldman
  • 14,885
  • 2
  • 14
  • 28