0

I have lots of JS arrays like the following:

 q = [{
      "v": "blah",
          "t": "asdfsdf",
 }, {
      "v": "basldfasdfd",
          "t": "blah",
 }...]

I'd like to assign unique id's to them, and then attach those id's to buttons, essentially. However, I'm not sure where I should put the id's without changing the structure of the JS array. I'm building an angular JS app and in the chrome dev tools, I've noticed a $$hashkey for each element. Does the entire array have a property like that? If so, how can I use it, and will it change if the array changes (which it will)?

I'd like to avoid further nesting, ie, I'd prefer to avoid having to do something like

q = {
  data: [whatever was above],
  meta: { id: 234234324, ... }
};

Is that the only way? If so, then in AngularJS, instead of doing ng-repeat="item in q", I would just do ng-repeat="item in q.data", right?

George Netu
  • 2,758
  • 4
  • 28
  • 49
thatandrey
  • 287
  • 5
  • 16

2 Answers2

0

Angular adds $$hashKey to keep track of your changes, so it knows when it needs to update the DOM. (more info)

q = {
  data: [whatever was above],
  meta: { id: 234234324, ... }
}; 

Is that the only way?

I don't see why i would use another structure, this one is good.

If so, then in angularJS, instead of doing ng-repeat="item in q", I would just do ng-repeat="item in q.data", right?

Yes

Community
  • 1
  • 1
jbigman
  • 1,200
  • 11
  • 24
0

If I understood your question correctly, you can use lodash's _.indexBy()

It will convert your array to an object that you can call by keys

var q = [{
    "v": "blah",
    "t": "asdfsdf",
}, {
    "v": "basldfasdfd",
    "t": "blah",
}];

// returns an object that has the value of v as the key
console.log(_.indexBy(q, 'v'));

// returns an object that has the value of t as the key
console.log(_.indexBy(q, 't'));

Here's an example: http://jsfiddle.net/wnnr0hza/

filype
  • 8,034
  • 10
  • 40
  • 66
  • I'm not too familiar with `lodash_.indexBy()`. Can you explain it a little or provide an example? Thanks! – thatandrey May 06 '15 at 21:59
  • @thatandrey added the lodash indexBy example – filype May 07 '15 at 07:57
  • Thanks, I see it now. Actually, what I wanted to do was index q as an object, not it's individual members, since I'll be having lots of q's. I guess there's really no better way than what I suggested as an option? – thatandrey May 07 '15 at 19:41