1

I have the below array of objects. if i do a console.log, i see this

[Object, Object, Object]
0:Object
     name: "Rick"
     Contact: "Yes"
1:Object
     name:"Anjie"
     Contact:"No"
2:Object
     name:"dillan"
     Contact:"Maybe"

I want the above array of object to be updated like this.

[Object, Object, Object]
0:Object
     name: "Rick"
     Contact: "Yes"
     id: 1
1:Object
     name:"Anjie"
     Contact:"No"
     id: 2
2:Object
     name:"dillan"
     Contact:"Maybe"
     id:3

As you can see, i have added id and it auto increments whenever a new object is present.

Can someone let me know how to do this dynamically ?

5
  • 1
    What have you tried? Maybe consider using a for loop and iterating through the objects, assigning the iterator to each. Commented May 26, 2016 at 23:02
  • @JacobBuczarski- i can iterate. but i dont know how to insert the id in there and auto increment it for every object Commented May 26, 2016 at 23:06
  • I don't see a reason to tag angularjs. Commented May 26, 2016 at 23:07
  • @Patrick There's no auto-increment in Javascript. You should use another variable to hold the highest ID, and increment it. Commented May 26, 2016 at 23:07
  • If you create a for loop, you can assign iterator+1. If there are already ids in some of the values, you would need to find the highest, and use that val + (iterator+1). Commented May 26, 2016 at 23:26

1 Answer 1

1

It's actually very simple. You can do it like this:

var objs = [{
  name: "Rick",
  Contact: "Yes"
}, {
  name: "Anjie",
  Contact: "No"
}, {
  name: "dillan",
  Contact: "Maybe"
}];

objs.forEach(function(obj, index) {
  obj.id = index + 1;
});

console.log(objs);

For each object in the objs array, it adds an id with the value of the index (+1 because the index starts at 0)

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

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.