1

I am trying to add property name and value from 'for loop'. However it is not working in object case. But if I use HTML form it works fine.

    var interestListsObj = {}
    interestLoop:function(interestList){
                var text = "";
                for(var i=0; i<interestList.length; i++) {
                    text += "<option value='"+interestList[i].machine_name+"'>"+ interestList[i].name + "</option>";
    /*line no 6*/   interestListsObj.interestList[i].machine_name =  interestList[i].name;  
                }
                $("#listOfInterest").html(text);    

                console.log(interestListsObj)                   

    },

In the above code if I remove the 'line no 6' then it works fine. But not sure what is wrong with the line no 6. The loop exit automatically without desire result.

6
  • Can you show us what interestList looks like? Are you getting any errors right now? Commented May 25, 2017 at 17:05
  • 1
    Use [] notation for creating and accessing dynamic properties. . won't work here. Change interestListsObj.interestList[i].machine_name to interestListsObj[interestList[i].machine_name] Commented May 25, 2017 at 17:05
  • you will have to declare interestListsObj.interestList[i] = {}; before line 6 if you are creating an object. Commented May 25, 2017 at 17:06
  • can you explan what exactly you are trying to do in line number 6 Note: interestListsObj your obj is empty so you can not read props of empty object Commented May 25, 2017 at 17:06
  • 1
    @ScottMarcus What I meant was he wants to use interestList[i].machine_name as a key for his object. He'll have to use the interestListsObj[interestList[i].machine_name] for that, . won't work Commented May 25, 2017 at 17:09

1 Answer 1

2

Issue is with your way of property assignment on the interestListsObj object.
If you want use a variable or an expression to create/access a property on your object use [] square bracket notation. Use . when your property name is simple javascript identifier.

Change your code to this:

interestListsObj[interestList[i].machine_name] =  interestList[i].name;
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, thanks for your answer. It works fine. I will keep in mind that for dynamic properties we need '[]' brackets.
@Santosh Glad I helped. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.