JSON中的嵌套键/值结构

用户名

我从服务获得以下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"));


编辑1

@Benny Bottema所建议Array.find存在兼容性问题。您可以添加一个polyfill,也可以使用诸如Array.filter和的其他方法Array.forEach但请注意,即使IE8不支持这些方法。

如果要使其与所有浏览器兼容,则应使用forfor..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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章