2

I would like to be able to type in "Hammerhead" to call the "Hammerhead Shark" object without its full name. Is this possible and if so how?

I tried using array.indexOf(string) though it doesn't really seem to help since it requires an exact match such as typing "Hammerhead Shark"

JS:

const JSON = require('animals.json');
var animals = Object.keys(JSON);

if (animals.indexOf("Hammerhead")) {
console.log(JSON["Hammerhead"].name);
}

JSON:

{
  "Hammerhead Shark": {
  "name": "Shark",
  "age": "300"
  },
  "Duck": {
  "name": "Duck",
  "age": "1000"
  }
}

I expect the output to be "Shark" instead of undefined.

Yazuki Rin
  • 113
  • 1
  • 12
  • 3
    You need to loop through the array, then you can check each one for the key you want. You can't access the object directly with a string that doesn't match. – jmargolisvt May 15 '19 at 13:11
  • 2
    That `JSON` [isn't actually JSON](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) - it's a plain JavaScript object. – VLAZ May 15 '19 at 13:13
  • Adding to @jmargolisvt comment, your if should have check for 0 or greater index as if that is the first key, it will return 0, which is falsey in JS – Rajesh May 15 '19 at 13:13
  • first let's clarify one thing, [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/), so what does your `const JSON` contain? json or an Object? Second: *"I would like to be able to type in "Hammerhead" to call the "Hammerhead Shark""* where do you want to type that? In your IDE? Are you talking about Intelligent code completion in your IDE? Or are we talking like autocompletition+fuzzy search for a form field in your Page? – Thomas May 15 '19 at 13:20

2 Answers2

1

It seems you want to get access the value in object. By its partial name.

  • Get the entries of object using Object.entries()
  • Find the key which includes() the given partial key.
  • return the second element of the found entry.

const obj = { "Hammerhead Shark": { "name": "Shark", "age": "300" }, "Duck": { "name": "Duck", "age": "1000" } }

function getValueByPartialKey(obj,key){
  return (Object.entries(obj).find(([k,v]) => k.includes(key)) || [])[1]
}

console.log(getValueByPartialKey(obj,"Hammerhead"))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

You can use string.includes(word) to return the name that matches the string that you're searching for, along with Array.filter iterates over the values too, and returns the result(s) you want.

Nnanyielugo
  • 401
  • 4
  • 13