kumaresan
kumaresan

Reputation: 83

Search in Javascript object by index string value

I am trying to iterate through an multidimensional object. I have string, which i have to match in the object index and get that value. for eg:

var datasets = {
    "usa:::west": {
        label: "USA",
        data: [[1988, 483994], [1989, 479060], [1990, 457648], [1991, 401949], [1992, 424705], [1993, 402375], [1994, 377867], [1995, 357382], [1996, 337946], [1997, 336185], [1998, 328611], [1999, 329421], [2000, 342172], [2001, 344932], [2002, 387303], [2003, 440813], [2004, 480451], [2005, 504638], [2006, 528692]]
    },        
    "russia:::north": {
        label: "Russia",
        data: [[1988, 218000], [1989, 203000], [1990, 171000], [1992, 42500], [1993, 37600], [1994, 36600], [1995, 21700], [1996, 19200], [1997, 21300], [1998, 13600], [1999, 14000], [2000, 19100], [2001, 21300], [2002, 23600], [2003, 25100], [2004, 26100], [2005, 31100], [2006, 34700]]
    }
};

In this case i only have the string "usa" wherease in the object the index is "usa:::west". How can i search it?

Upvotes: 0

Views: 5961

Answers (2)

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

As I understood correctly, this is perhaps something you're after for:

var getKeys = function(query) {
  var keys = Object.keys(datasets).filter(function(key) {
    return !!~key.indexOf(query);
  });

  return keys;
};

where getKeys('usa'); returns an array ['usa:::west']. And for instance getKeys(':::'); will return ['usa:::west', 'russia:::north']

Upvotes: 2

Val
Val

Reputation: 217304

One way to do it would be to iterate over the keys of your dataset and try to match the beginning of the key:

var search = 'usa';
var keys = Object.keys(datasets);
for (var key in keys) {
    if (key.indexOf(search) === 0) {
        var values = datasets[key];
        // from here on you have access to label, data, etc
    }
}

Upvotes: 0

Related Questions