这个问题在这里已有答案:
我跟随json
var dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
我可以像这样访问数组的第二个元素:
dictionary[1].value
它返回10,这是历史主题的分数。我正在寻找的方式是我可以通过“历史”这个词来访问它,我的意思是我需要这样的代码:
dictionary["History"].value
我怎样才能做到这一点?
好的,所以这是一个黑客。你可以使用Array
作为Object
并插入你想要的任何key
。您可以将forEach
应用于它并将keys
与properties
绑定,如下所示。
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);
注意:这只是一个Hack,如果出现重复条目,则会失败。
编辑
重复键的解决方案
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"]);
通过使用find()
迭代您的数组。
find()方法返回数组中第一个满足提供的测试函数的元素的值。否则返回undefined。
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)
有不止一种方法可以做到这一点,但这一方法是最直接和简洁的。
试试这个:
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'));
如果遍历您的对象数组并找到与其key
匹配的对象到searchKey
并返回结果。
或者,您可以将对象数组转换为单个对象,然后直接引用它:
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);