0

I have a data array like this,

tourGuide: [
    {"location": "london"},
    {"location": "paris"},
    {"location": "frankfurt"}
]

I want to rewrite the tourGuide so that it will contain the indices too. so it will become something like:

tourGuide: [
    {"location": "london", "index":0},
    {"location": "paris", "index":1},
    {"location": "frankfurt","index":2}
]

I tried this:

var x, l=0;
for(x in tourGuide){
    tourGuide["index"] = l;
    l++;
}

but that may not be right approach.

1
  • Why would you want to do this? If you decide to change the order of the elements how are you going to keep up with the index? If you want to get the object from the array you need to know the index anyway. Commented May 18, 2012 at 2:16

3 Answers 3

2
var x, l=0;

for(x in tourGuide){

tourGuide[x]["index"] = l;
l++;

}
Sign up to request clarification or add additional context in comments.

Comments

1

I would suggest you forget about the location property and just make a simple array. Unless you intend to add more properties later, a regular array will supply the numeric index for you. Just do:

var output = array();
for (var i=0; i<tourGuide.length; i++) {
  // Just stick each of the locations onto a plain old array
  output.push(tourGuide[i].location;
}

console.log(output);

Comments

1

Try this:

for(var i=0;i<tourGuide.length;i++){
    tourGuide[i].index=i
}

//----or more simplified...----

var i=0;
for(;i<tourGuide.length;){
    tourGuide[i].index=i++
}

LIVE DEMO: http://jsfiddle.net/DerekL/qvdzR/

But actually, you don't really have to create an index, since they are in an array, they already have an index value.

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.