0

I try to create a new object with jquery each but only the last element of my looped is getting added to my object

var selectArray ={}; 
    $.each(response, function( i, x ){
          selectArray['id'] = x.id;
          selectArray['text'] = x.name;                            
    });
 console.log(selectArray);

2 Answers 2

3

Use an array and push a new object containing the keys and values:

var selectArray = []; 
$.each(response, function( i, x ){
      selectArray.push({"id":x.id, "name":x.name})                           
});
console.log(selectArray);
Sign up to request clarification or add additional context in comments.

2 Comments

Objects don't have a push method. Arrays do, though.
I don't think the user wants to just make a clone of the input array (which this effectively does, unless the goal is to create objects leaving out all properties other than id and name). "Associative" suggests doing a map of some kind.
0

You've said "associative array" (that's not a term used with JavaScript; they're just "objects"), so I'm guessing you want to create an object where selectArray['some id'] will give you name:

var selectArray = {}; 
$.each(response, function( i, x ){
    selectArray[x.id] = x.name;
});
console.log(selectArray);

So for instance, if your response contained three items (id "tjc" => name "T.J. Crowder", id "joeblow" => name "Joe Blow", and id "bozscaggs" => name "Boz Scaggs"), you'd end up with an object that looked like this:

{
    "tjc":       "T.J. Crowder",
    "joeblow":   "Joe Blow",
    "bozscaggs": "Boz Scaggs"
}

and

selectArray['tjc']

...would give you "T.J. Crowder".

Complete Example: Live Copy

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Creating a lookup object</title>
</head>
<body>
  <p>Look in the console</p>
  <script>
    (function() {
      var response = [
        {id: "tjc", name: "T.J. Crowder"},
        {id: "joeblow", name: "Joe Blow"},
        {id: "bozscaggs", name: "Boz Scaggs"}
      ];
      var selectArray = {}; 
      $.each(response, function( i, x ){
        selectArray[x.id] = x.name;
      });
      console.log(selectArray);
    })();
  </script>
</body>
</html>

Comments

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.