6

Currently, I have an array of objects, that looks like this:

var arr = [{
            id: UNIQUE_ID,
            title: 'TITLE'
          }, {
            id: UNIQUE_ID,
            title: 'TITLE'  
          }];

What is bothering me here, is that in particular cases I have to loop through the array and display data for matching ID. I want to just fetch everything for that particular object, thas has the ID I want, and that's it. It would be a lot easier for me if the array looked more like this:

var arr = [{
            id: {
              title: 'TITLE'
            },
            id: {
              title: 'TITLE'
            }
          }]

The ID comes from a result of a method that generates a random number, so I'll need to put a variable or a method call for this id.

I'm not sure this is possible, since I found no particular example on this, but I'd like to hear another solutions as well.

2
  • 1
    How does it help, you again need to traverse each object in an array. Instead, convert an array into object (2nd one), so that yo don't need to loop it. Commented Mar 13, 2014 at 12:41
  • does your "outer" container have to be an array? Making it an object allows you to just use my_data[key] to access objects. You lose the ability to do "array-like" things like push and pop, but if you don't need them, just use an object. Commented Mar 13, 2014 at 12:44

3 Answers 3

19

You can do that, by removing the array entirely, just using an object:

var items = {};
items["some id"] = {title: 'first title'};
items["another id"] = {title: 'second title'};

Or if you have the key in a variable:

var key = "a third id";
items[key] = {title: 'third title'};

Later, if you wanted to look up one of those entries based on a key:

var key = "another id";

You'd do it like this:

console.log(items[key].title); // "second title" (if key is "another id")

If you need to know what all of the keys in the object are, you can use Object.keys:

var arrayOfKeys = Object.keys(obj);

(Note that Object.keys is an ES5 feature; on older browsers, you need to add a shim for it, which is trivial.)

Note the way I populated the object in the first code block above. If you can hardcode the keys, you can do that with an object initializer:

var items = {
    "some id":    {title: 'first title'},
    "another id": {title: 'second title'}
};

...but you can't do it that way if you want to use a variable for the key name, because you can't put the variable on the left-hand side of the : (it'll look like a literal key name). That is, if you have

var key = "a third id";

then this won't work:

var items {
    key: {title: "third title"} // <==== Doesn't do what we want
};

The key would be "key", not "a third id" (just like the title key we've been using). That's why in the first block above, I created the object and then set the properties separately afterward.

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

1 Comment

That was what I was looking for! Though, I'm not sure I'll use it, since I'm tied to using AngularJS here and I need to show info from this array with ng-repeat and use the $watch method to look for changes in that array. Unfortunately, they both don't work the same with objects as they do with arrays. Thanks anyway, that's another problem I'll have to cope with.
0

What you're asking for far is call indexing. You can easily achieve it by structuring your data as such:

var arr = {
        1: {
          title: 'TITLE'
        },
        2: {
          title: 'TITLE'
        }
      };

You don't even have to traverse the now indexed array, since each entry is accessible through its index:

var needle = array[id];

5 Comments

"...the now indexed array..." That isn't an array, it's a non-array object.
Well, technically it's an object, but since you can access it as an array (array[key]), it sure behaves like one ;)
@ Samy: No, this[that] is not accessing it "like an array." That's basic JavaScript object property access notation, nothing to do with arrays except arrays use it.
@T.J.Crowder: All right, you're the boss ;) appologies. What about the dot notation though (object.key)? (I come from Java, hence the confusion)
@ Samy: They're both object property accessors. Dot notation takes a literal name (obj.foo), bracketed notation takes a string (obj["foo"]), coercing whatever you give it if it's not one (even with arrays, because they're not really arrays).
0

With the help of UnderscoreJs:

var arr= [{
    id: '1',
    title: 40
}, {
    id: '2',
    title: 40
}, {
    id: '1',
    title: 60
}];
var res = _.groupBy(arr, function(x){ return x.id; });
res["1"];

Result:

[{
    id: '1',
    title: 40
}, {
    id: '1',
    title: 60
}]

http://jsbin.com/jifabuva/1/edit

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.