0

I have a JSON object like this

myObj = {
"knowncount": [{
    "id": "planet",
    "knownCount": 8,
    "updateDate": "24/08/2006",
    "rel": "https://api.le-systeme-solaire.net/rest/knowncount/planet"
}, {
    "id": "dwarfPlanet",
    "knownCount": 5,
    "updateDate": "24/08/2006",
    "rel": "https://api.le-systeme-solaire.net/rest/knowncount/dwarfPlanet"
}, {
    "id": "asteroid",
    "knownCount": 1027022,
    "updateDate": "11/11/2020",
    "rel": "https://api.le-systeme-solaire.net/rest/knowncount/asteroid"
}, {
    "id": "comet",
    "knownCount": 3690,
    "updateDate": "11/11/2020",
    "rel": "https://api.le-systeme-solaire.net/rest/knowncount/comet"
}]}

How can I search my object to find where the key is 'id' and then print its value for knownCount?

Example. If 'id' == 'planet'

// 8

I've tried to covert to array to use array functions like array.find() but this doesn't seem to work. I check type with typeof and continue to get type object. What is the correct way to change to array or is there a comparable way to do this with objects or must I iterate over the object and create a set or something similar?

user2016569
  • 26
  • 1
  • 8

4 Answers4

0

You could just loop through the object and test fo the id:

function getId(myId){
let a =myObj.knowncount
for (el in a){
   if(el.id==myId)
return el
}
}
MoPaMo
  • 517
  • 6
  • 24
  • Why do you think so? – MoPaMo Jan 27 '21 at 06:06
  • Do you realize that I (just like everyone else) can see you fixed your mistake after my comment? – Yevhen Horbunkov Jan 27 '21 at 09:12
  • And back to the 'why'-question, you might find the following [quick test](https://codepen.io/ygorbunkov/pen/RwGXdRL?editors=0010) I've set up for you to actually prove your solution **still** won't work. Feel free to use it for getting your code valid. – Yevhen Horbunkov Jan 27 '21 at 09:45
0
myObj
 .knowncount
 .find(({ id }) => id === 'planet')
 .knownCount;
Meroz
  • 859
  • 2
  • 8
  • 28
0

Try it

const res = myObj.knowncount.find(el => el.id === 'planet')?.knownCount || 'Planet not found';
console.log(res);

You can't use finddirectly on the myObj because it's an Object, and not an Array.

myObj = {
"knowncount": [{
    "id": "planet",
    "knownCount": 8,
    "updateDate": "24/08/2006",
    "rel": "https://api.le-systeme-solaire.net/rest/knowncount/planet"
}, {
    "id": "dwarfPlanet",
    "knownCount": 5,
    "updateDate": "24/08/2006",
    "rel": "https://api.le-systeme-solaire.net/rest/knowncount/dwarfPlanet"
}, {
    "id": "asteroid",
    "knownCount": 1027022,
    "updateDate": "11/11/2020",
    "rel": "https://api.le-systeme-solaire.net/rest/knowncount/asteroid"
}, {
    "id": "comet",
    "knownCount": 3690,
    "updateDate": "11/11/2020",
    "rel": "https://api.le-systeme-solaire.net/rest/knowncount/comet"
}]}

const res1 = myObj.knowncount.find(el => el.id === 'planet')?.knownCount || 'Planet not found';
console.log('Know planet count:', res1);
const res2 = myObj.knowncount.find(el => el.id === 'planetX')?.knownCount || 'Planet not found';
console.log('Unknown planet count:', res2);
  • This code will throw Referrence Error if `id` value you search for is never found. – Yevhen Horbunkov Jan 26 '21 at 21:24
  • What you have to show if the planet isnt found? – Israel Bessa Jan 26 '21 at 21:26
  • Personally, I don't need anything. I just pointed out that solution failing with error when desired result is not found (which may be pretty common thing) is not that much robust. – Yevhen Horbunkov Jan 26 '21 at 21:28
  • I updated my answer, try it with a unknown planet please – Israel Bessa Jan 26 '21 at 21:29
  • That would've been much easier ***to try*** if you would make it [executable snippet](https://stackoverflow.blog/2014/09/16/introducing-runnable-javascript-css-and-html-code-snippets/). – Yevhen Horbunkov Jan 26 '21 at 21:30
  • And, by the way, returning some message string may be confusing. I doubt there's normally something that will consume that string properly, but there may certainly be the case, when you would need to evaluate the outcome (whether truthy or falsy) and this string may lead to unexpected truthy value. – Yevhen Horbunkov Jan 26 '21 at 21:34
  • Furthermore, if there exists an entry with `id: 'planet'` and `knownCount: 0` (absolutely valid, I would say), you will also get `planet not found`-message. – Yevhen Horbunkov Jan 26 '21 at 21:37
0

Use this getKnownCount function to get the known count.

function getKnownCount(Id) {
    let knownCountArray = myObj.knowncount;
    for (let i = 0; i < knownCountArray.length; i++) {
      if ((knownCountArray[i].id == Id)) {
        return knownCountArray[i].knownCount;
      }
    }
    return "Not found";
  }

As,

getKnownCount("planet")

or you can just simply search "planet" via the find method.

myObj.knowncount.find(el => el.id == 'planet')?.knownCount || 'Not found';
Rohit Nishad
  • 2,570
  • 2
  • 22
  • 32
  • Your second snippet will return `Not found` for `{id: 'planet', knownCount: 0}` – Yevhen Horbunkov Jan 26 '21 at 21:53
  • @YevgenGorbunkov I test it, it works fine for me can you describe more clearly what is not working for you. – Rohit Nishad Jan 27 '21 at 06:15
  • *'> it works'*, no, it doesn't, because it may never go further the first item, if you would [have actually tested that](https://codepen.io/ygorbunkov/pen/QWKeYQm?editors=0010) you would figure that out – Yevhen Horbunkov Jan 27 '21 at 09:06
  • @YevgenGorbunkov yeah, there is some issue I fixed it, now it work. – Rohit Nishad Jan 27 '21 at 16:58
  • I think you forget to accept this answer if you don't get the answer let me know. – Rohit Nishad Jan 28 '21 at 12:48
  • I don't think OP has forgotten to accept this particular answer, since your code (almost identical to 2 answers, posted almost half an hour before you and became actually working almost 1 day later) doesn't seem to contribute much into solving their issue for [chronological reasons](https://stackoverflow.com/questions/65909370/how-to-find-value-in-json-object-array/65909717?noredirect=1#comment116533582_65909370). – Yevhen Horbunkov Jan 28 '21 at 13:51
  • Ok.... i was say it because as far now there isn't any accepted answer – Rohit Nishad Jan 28 '21 at 15:02
  • BTW, is there any issues with it, now? – Rohit Nishad Jan 28 '21 at 15:03
  • *'> ..there isn't any accepted answer'* well, that's because by the time the problem was actually solved none of them was functional (or they had some critical caveats). As for your particular post, your `.find()`-based solution may still return `'Not found'`-message for some valid cases (you may refer to my earlier comments or the test suite I have shared for details). Other than that, I wouldn't return a string upon no match (since `undefined` may rather be expected), because that find result may still be evaluated as truthy, hence be misleading in certain use cases. – Yevhen Horbunkov Jan 28 '21 at 15:16