如何使用Javascript数组从涉及多个键值对的JSON中检索特定值

时间:2017-12-18 18:07:31

标签: javascript

我跟随json

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

我可以像这样访问数组的第二个元素:

dictionary[1].value

它返回10,这是历史主题的分数。 我正在寻找的是通过“#34;历史"”这个词来访问它的方式。本身,我的意思是我需要这样的代码:

dictionary["History"].value

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:4)

好的,所以这是一个黑客。您可以将Array用作Object并插入所需的任何key。您可以对其应用forEach并将keysproperties绑定在一起,如下所示。

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);

注意:这只是一个黑客,如果有重复的条目,将会失败。

<强>被修改

重复密钥时的解决方案

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"]);

答案 1 :(得分:2)

使用find()迭代您的数组。

来自MDN Array.prototype.find()

  

find()方法返回数组中第一个满足提供的测试函数的元素的值。否则返回undefined。

&#13;
&#13;
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)
&#13;
&#13;
&#13;

有多种方法可以做到这一点,但这个方法最直接,最简洁。

答案 2 :(得分:1)

试试这个:

&#13;
&#13;
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'));
&#13;
&#13;
&#13;

如果遍历您的对象数组并找到与其key匹配的对象并返回结果。

或者您可以将对象数组转换为单个对象,然后直接引用它:

&#13;
&#13;
searchKey
&#13;
&#13;
&#13;