Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array of Objects with custom keys

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.

like image 692
abpetkov Avatar asked Mar 13 '14 12:03

abpetkov


Video Answer


1 Answers

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.

like image 190
T.J. Crowder Avatar answered Sep 27 '22 21:09

T.J. Crowder