-2

I have an object that looks something like:

var myObj = {
some : {},
stuff : 123,
in : {
    here : {
       variables : 'stuffety stuff',
       variables : 'stuffety stuff',
       variables : 'stuffety stuff',
       variables : 'stuffety stuff',
       image1 : 'img1.jpg',
       image2 : 'img2.jpg',
       image3 : 'img3.jpg',
       imageN : 'imgN.jpg',
       ...
       variables : 'stuffety stuff',
       variables : 'stuffety stuff',
    }
  }
}

Where N can be any given Number. I'm trying to get all the keys with "image" in it and push it into an array. So that the Result should look like:

images['img1.jpg','img2.jpg','img3.jpg','imgN.jpg'...]

How do i find those numbered keys, when not knowing how many of them there are. They can also be unordered. (image2 missing for example)

denns
  • 1,105
  • 1
  • 11
  • 24
  • 1
    And you're here because you want us to implement it for you? – zerkms Oct 13 '15 at 10:47
  • more or less. i'm looking for an elegant implementation. – denns Oct 13 '15 at 10:49
  • Well, it's a community to help developers not to do their job for free. – zerkms Oct 13 '15 at 10:50
  • what's the problem? i don't know how to get to these keys. i'm not going to pay my rent with this piece of code 0_o – denns Oct 13 '15 at 10:54
  • So ask a particular question then. Split your task into subtasks and solve them separately one after another. 1) get all keys 2) find all keys that match pattern 3) retrieve data from the original object using the keys from #2. These are the basic steps. – zerkms Oct 13 '15 at 10:55
  • Exaclty. But I don't know how to solve step 2) – denns Oct 13 '15 at 10:58
  • So why did not you ask it? For the step 2 you don't need to explain the whole problem, but "I have an array, how to filter few values out of it". Do you seriously not see the difference between "help me solving this small subtask" and "solve the whole thing for me"? – zerkms Oct 13 '15 at 10:58
  • just wanted to keep it simple. sorry for that. – denns Oct 13 '15 at 11:00

2 Answers2

1

Here's a simple solution using a for loop. See this question for the original code.

var extracted = [];
for (var p in myObj.xin.here) {
    if (myObj.xin.here.hasOwnProperty(p) && p.indexOf("image") > -1) {
        extracted.push(p);
    }
}
Community
  • 1
  • 1
Arj
  • 1,981
  • 4
  • 25
  • 45
0

You can use the Object method Object.keys() to get the keys inside your object.

Object.keys(myObj.in.here)

Above code will give you the expected result.