4

I have following json

var dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]

I can access for instance the second element of the array like this:

dictionary[1].value

it returns 10 which is the score of the History subject. What I'm looking for is the way so that I can access it by the word "History" itself, I mean I need a code like this:

dictionary["History"].value

How can I achieve that?

Muhammad Musavi
  • 2,512
  • 2
  • 22
  • 35

3 Answers3

4

Ok, so here is a hack. You can use Array as an Object and insert any key you want. You can apply forEach to it and bind keys with properties like below.

var dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]

dictionary.forEach(function(item) {
  dictionary[item.key] = item;
});

console.log(dictionary["History"].value);

Note: This is just a Hack and will fail in case of duplicate entries.

Edited

Solution in case of duplicate keys

var dictionary = [{
  "key": "Math",
  "value": "20"
}, {
  "key": "History",
  "value": "10"
}, {
  "key": "Chemistry",
  "value": "12"
}, {
  "key": "Chemistry",
  "value": "13"
}]

dictionary.forEach(function(item) {
  if (dictionary[item.key] && !Array.isArray(dictionary[item.key])) {
    dictionary[item.key] = [dictionary[item.key]];
    dictionary[item.key].push(item);
  } else if (dictionary[item.key] && Array.isArray(dictionary[item.key])) {
    dictionary[item.key].push(item);
  } else {
    dictionary[item.key] = item;
  }
});

console.log(dictionary["Chemistry"]);
Vipin Kumar
  • 6,441
  • 1
  • 19
  • 25
  • But the first solution makes weird issue when the key is integer specially if it's a nested object, it will create an array which has length as big as key, for instance execute following snippet in console, then dictionary will have 20121222 length!!! `var dictionary = []; var stringifiedItem = "[{\"_key\":\"20181222\",\"_value\":[{\"dayNo\":\"1\",\"date\":\"20181222\",\"entraceTime\":[\"7\",\"10\"],\"exitTime\":[\"16\",\"00\"],\"restTime\":[\"00\",\"35\"]}]}]"; dictionary = JSON.parse(stringifiedItem); dictionary.forEach(function (item) { dictionary[item._key] = item; });` – Muhammad Musavi Dec 25 '18 at 11:58
3

By using find() to iterate over your array.

From MDN Array.prototype.find():

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

const dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]

const result = dictionary.find(item => {
  // if this returns `true` then the currently 
  // iterated item is the one found
  return item.key === 'History'
})

console.log(result)

There's more than one way to do this but this one is the most straightforward and succinct.

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
1

Try this:

var dictionary = [
  {"key":"Math","value":"20"},
  {"key":"History","value":"10"},
  {"key":"Chemistry","value":"12"}
];

function getValue(searchKey) {
  var retVal;
  dictionary.some(item => {
    if (item.key === searchKey) {
      retVal = item.value;
      return true;
    }
  });
  
  return retVal;
}

console.log(getValue('History'));

If goes through your array of objects and finds the object that matches its key to your searchKey and returns the result.

Or you can convert your array of objects into a single object and then reference it directly:

    var dictionary = {};
    
    [
      {"key":"Math","value":"20"},
      {"key":"History","value":"10"},
      {"key":"Chemistry","value":"12"}
    ].forEach(item => {dictionary[item.key] = item.value;});

    console.log(dictionary.History);
Intervalia
  • 10,248
  • 2
  • 30
  • 60