不确定发布规则,但我会告诉你,这是重复的问题,但我想问这是否是最佳实践的方法?
这很容易实现。如果您需要多次快速访问,请创建一个由属性名称为键的映射。
下面是一个函数,它接受数组并构建键控映射。它不是通用的,但你应该能够修改它以符合你自己的使用。
/**
* Given an array and a property name to key by, returns a map that is keyed by each array element's chosen property
* This method supports nested lists
* Sample input: list = [{a: 1, b:2}, {a:5, b:7}, [{a:8, b:6}, {a:7, b:7}]]; prop = 'a'
* Sample output: {'1': {a: 1, b:2}, '5': {a:5, b:7}, '8': {a:8, b:6}, '7':{a:7, b:7}}
* @param {object[]} list of objects to be transformed into a keyed object
* @param {string} keyByProp The name of the property to key by
* @return {object} Map keyed by the given property's values
*/
function mapFromArray (list , keyByProp) {
var map = {};
for (var i=0, item; item = list[i]; i++) {
if (item instanceof Array) {
// Ext.apply just copies all properties from one object to another,
// you'll have to use something else. this is only required to support nested arrays.
Ext.apply(map, mapFromArray(item, keyByProp));
} else {
map[item[keyByProp]] = item;
}
}
return map;
};
@jondavidjohn - 您可以使用这个JavaScript库,DefiantJS(http://defiantjs.com),通过XPath在JSON结构中进行过滤匹配。将其放入JS代码中:
var data = [
{
"restaurant": {
"name": "McDonald's",
"food": "burger"
}
},
{
"restaurant": {
"name": "KFC",
"food": "chicken"
}
},
{
"restaurant": {
"name": "Pizza Hut",
"food": "pizza"
}
}
].
res = JSON.search( data, '//*[food="pizza"]' );
console.log( res[0].name );
// Pizza Hut
这里有一个可用的 fiddle;
http://jsfiddle.net/hbi99/weKVL/
DefiantJS 通过方法 "search" 扩展全局对象,并返回匹配项数组(如果没有找到匹配项,则为空数组)。您可以使用 XPath 评估器在此处尝试该库和 XPath 查询: