1

I have a literal array that is loaded when the page loads... See below:

<script type="text/javascript">
var members = [
    {
       name:"Alan Lim",
       id:"54700f06-a199-102c-8976-b1732b7ffc74",
       positions:[
          {
             id:"4cdeb2a2-8897-102d-80ee-95364de284f0"
          }
       ]
    },
    {
       name:"Ben Sinclair",
       id:"ed34b5a4-9b2f-102c-8475-9e610b13400a",
       conflict:"true",
       positions:[
          {
             id:"f00c2128-8895-102d-80ee-95364de284f0"
          },
          {
             id:"f00c68ea-8895-102d-80ee-95364de284f0"
          },
          {
             id:"4cde6824-8897-102d-80ee-95364de284f0"
          },
          {
             id:"4cde9ea2-8897-102d-80ee-95364de284f0"
          }
       ],
       locations:[
          {
             id:"88fb5f94-aaa6-102c-a4fa-1f05bca0eec6"
          },
          {
             id:"930555b0-a251-102c-a245-1559817ce81a"
          }
       ]
    },
    {
       name:"Debbie Wright",
       id:"fa49307a-9cfb-102d-bd08-842c500d506d"
    }
]
</script>

Is there anyway to edit the array without reloading the page? For example, I want to add conflict:"true" to Alan Lim...

E.g:

Change this:

    {
       name:"Alan Lim",
       id:"54700f06-a199-102c-8976-b1732b7ffc74",
       positions:[
          {
             id:"4cdeb2a2-8897-102d-80ee-95364de284f0"
          }
       ]
    },

To this:

    {
       name:"Alan Lim",
       id:"54700f06-a199-102c-8976-b1732b7ffc74",
       conflict:"true",
       positions:[
          {
             id:"4cdeb2a2-8897-102d-80ee-95364de284f0"
          }
       ]
    },

Trust that makes sense :) The reason for this is because I use other JavaScript to pull information from this array. When I make a change with the other JavaScript I want to add and subtract to this array to reflect the changes...

1
  • You are allowed to dynamically add properties to an array element. Commented Sep 7, 2010 at 11:52

2 Answers 2

6

You can loop through to find the member you want (by name it seems given the question) then edit it, like this:

for(var i=0; i<members.length; i++) {
  if(members[i].name == "Alan Lim")
    members[i].conflict = "true";
}

You can give it a try here, or make it a bit more generic like this:

function setProp(name, prop, value) {
  for(var i=0; i<members.length; i++) {
    if(members[i].name == name)
       members[i][prop] = value;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

3

Since your array is numerically indexed, Can you not just do:

members[0]['conflict'] = "true";

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.