Kyle Adams Kyle Adams - 6 months ago 15
jQuery Question

How do I get they keys and the values from the object and return an array?

So let me give you an example object:

{
example_98: value,
example_7658: value,
example_2764: value
key: value,
otherKey: otherValue
}


I want to search this object for all the
example_x
and return an array that looks something like:

[{example_98: value}, ...]


What is the easiest way to do this in Javascript? I prefer pure javascript but I do have access to jquery if that makes it easier.

Answer

You can get all of the keys of an object the following way:

var obj = {
  example_98: value,
  example_7658: value,
  example_2764: value
  key: value,
  otherKey: otherValue
}

console.log(Object.keys(obj)); // ['example_98', 'example_7658', ...]

To get all of the objects whose keys match a certain value, you can do this:

var regEx = /example_/;

var onlyExamples = Object.keys(obj)
  .filter(function(o) {
    // only return keys that match regEx
    return o.test(regEx);
  })
  .map(function(o) {
    // return { key: value }
    return { o: obj(o) };
  });

This will return an array of objects with only those values that match the regular expression, so your example object would return [{example_98: value }, {example_7658: value }, {example_2764: value}].

Edit

As @andlrc pointed out, you can refine your regex to to select only those keys that start with "example" by using: var regEx = /^example_/;

Comments