我从服务获得以下JSON结构:
{
"prop": [
{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
},
{
"key": "BAR",
"value": "Bar is bad, really bad"
}
]
}
我需要一个函数,该函数以例如BAR为参数,并输出“ Bar is bad,..”,我该如何实现?欢迎Lodash /下划线或VanillaJS。
您可以使用Array.find
查找必要的对象,然后返回其值
var d = {
"prop": [{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
}, {
"key": "BAR",
"value": "Bar is bad, really bad"
}]
}
function FindValue(value) {
var _tmp = d.prop.find(function(o) {
return o.key === value
});
return _tmp ? _tmp.value : "No object found";
}
console.log(FindValue("BAR"));
console.log(FindValue("BAR1"));
console.log(FindValue("FOO"));
如@Benny Bottema所建议,Array.find
存在兼容性问题。您可以添加一个polyfill,也可以使用诸如Array.filter
和的其他方法,Array.forEach
但请注意,即使IE8不支持这些方法。
如果要使其与所有浏览器兼容,则应使用for
或for..in
作为它们在所有浏览器中的标准配置。
对于版本
var d = {
"prop": [{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
}, {
"key": "BAR",
"value": "Bar is bad, really bad"
}]
}
function FindValue(value) {
for (var i=0;i<d.prop.length;i++){
if(d.prop[i].key === value) return d.prop[i].value;
}
}
console.log(FindValue("BAR"));
console.log(FindValue("BAR1"));
console.log(FindValue("FOO"));
for..in版本
注意,for..in
更适合于循环对象的键。
var d = {
"prop": [{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
}, {
"key": "BAR",
"value": "Bar is bad, really bad"
}]
}
function FindValue(value) {
for (var i in d.prop){
if(d.prop[i].key === value) return d.prop[i].value;
}
}
console.log(FindValue("BAR"));
console.log(FindValue("BAR1"));
console.log(FindValue("FOO"));
for..of版本
如果您使用的是ES6,那么您甚至可以尝试...
var d = {
"prop": [{
"key": "FOO",
"value": "Foo is wonderfull, foo is great"
}, {
"key": "BAR",
"value": "Bar is bad, really bad"
}]
}
function FindValue(value) {
for (var _o of d.prop){
if(_o.key === value) return _o.value;
}
}
console.log(FindValue("BAR"));
console.log(FindValue("BAR1"));
console.log(FindValue("FOO"));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句