Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve an specific value from a JSON involving multiple key value pairs using Javascript array [duplicate]

Tags:

javascript

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?

like image 417
Muhammad Musavi Avatar asked Jan 29 '23 00:01

Muhammad Musavi


1 Answers

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"]);
like image 103
Vipin Kumar Avatar answered Feb 05 '23 18:02

Vipin Kumar