JSON中的嵌套键/值结构

时间:2016-07-21 07:41:51

标签: javascript json underscore.js lodash

我从服务中获得以下JSON结构:

{
    "prop": [
        {
            "key": "FOO",
            "value": "Foo is wonderfull, foo is great"
        },
        {
            "key": "BAR",
            "value": "Bar is bad, really bad"
        }
    ]
}

我需要一个函数,它可以作为参数,例如BAR和输出" Bar不好,...",我怎样才能做到这一点?欢迎使用Lodash / undercore或VanillaJS。

7 个答案:

答案 0 :(得分:3)

您可以使用Textview查找必要的对象,然后返回其值

Array.find

编辑1

根据@Benny Bottema的建议,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"));存在兼容性问题。您可以添加polyfill,也可以使用Array.findArray.filter等其他方法,但请注意,IE8中不支持这些方法。

如果要使其与所有浏览器兼容,则应使用Array.forEachfor,因为它们是浏览器的标准版。

适用于版本

for..in

for..in version

注意,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..of version

如果您使用的是ES6,那么您甚至可以尝试for..of

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

参考

答案 1 :(得分:1)

var filteredArray = { "prop": [{ "key": "FOO", "value": "Foo is wonderfull, foo is great" }, { "key": "BAR", "value": "Bar is bad, really bad" }] };
function getByKey(findKey,filteredArray){
    if(filteredArray.length){
            var result = filteredArray.filter(function(x){
                return x.key === findKey
            });
            if(result && result.length){return result[0].value}
    }
}
getByKey('BAR',filteredArray.prop)

但该函数只返回第一个过滤的Object的值;

答案 2 :(得分:0)

我是用JAVASCRIPT写的:

&#13;
&#13;
var d = {
  "prop": [{
    "key": "FOO",
    "value": "Foo is wonderfull, foo is great"
  }, {
    "key": "BAR",
    "value": "Bar is bad, really bad"
  }]
}

obj = d;
parm = 'BAR'
for (item in obj["prop"]) {
  if (parm == item['key']) {
    console.log(item['value'])
  }
}
&#13;
&#13;
&#13;

要查看的步骤: -

  • 首先将JSON解析为Object
  • 然后迭代&#34; prop&#34;
  • 比较密钥和参数(&#34; BAR&#34;)
  • 如果匹配打印值

答案 3 :(得分:0)

现代纯javascript:

function getValue(theObject, keyValue) {
  return theObject.prop
    .filter(function(x){ // find all elements with the wanted key
      return x.key == keyValue;
    })
    .map(function(x){ // return only the value
      return x.value;
    })[0]; // Assuming no duplicate keys just return first item
}

注意:数组方法.filter().map()返回数组。

Old-school for loop:

function getValue(theObject, keyValue) {
  var p = theObject.prop;

  for (var i=0; i<p.length; i++) {
    var item = p[i];
    if (item.key == keyValue) {
      return item.value;
    }
  }
}

有趣的是,这比上面的第一种方法更快,因为它会在找到匹配后立即停止处理prop数组。

答案 4 :(得分:0)

您可以使用lodash#find按键获取值。

> PRAGMA user_version;  
> PRAGMA user_version = 1;

function getValueByKey(array, key) {
  return (_.find(array, { key: key }) || {}).value;
}

var result = getValueByKey(data.prop, 'BAR');
var data = {
    "prop": [
        {
            "key": "FOO",
            "value": "Foo is wonderfull, foo is great"
        },
        {
            "key": "BAR",
            "value": "Bar is bad, really bad"
        }
    ]
};

function getValueByKey(array, key) {
  return (_.find(array, { key: key }) || {}).value;
}

var result = getValueByKey(data.prop, 'BAR');

console.log(result);

答案 5 :(得分:0)

易。

<强> Lodash

&#13;
&#13;
var data = {
    "prop": [
        {
            "key": "FOO",
            "value": "Foo is wonderfull, foo is great"
        },
        {
            "key": "BAR",
            "value": "Bar is bad, really bad"
        }
    ]
}

function getValueForKey(key) {
  return _.result(_.find(data.prop, { key: key }), 'value') || "unknown key: " + key;
}

document.write(getValueForKey("FOO") + "<br/>");
document.write(getValueForKey("BAR") + "<br/>");
document.write(getValueForKey("FOOBAR"));
&#13;
<script src="https://cdn.rawgit.com/lodash/lodash/4.13.1/dist/lodash.core.min.js"></script>
&#13;
&#13;
&#13;

<强>下划线

&#13;
&#13;
var data = {
    "prop": [
        {
            "key": "FOO",
            "value": "Foo is wonderfull, foo is great"
        },
        {
            "key": "BAR",
            "value": "Bar is bad, really bad"
        }
    ]
}

function getValueForKey(key) {
  return _.result(_.find(data.prop, { key: key }), 'value', "unknown key: " + key);
}

document.write(getValueForKey("FOO") + "<br/>");
document.write(getValueForKey("BAR") + "<br/>");
document.write(getValueForKey("FOOBAR"));
&#13;
<script src="http://underscorejs.org/underscore.js"></script>
&#13;
&#13;
&#13;

普通javascript (使用filter,主流浏览器支持)

&#13;
&#13;
var data = {
    "prop": [
        {
            "key": "FOO",
            "value": "Foo is wonderfull, foo is great"
        },
        {
            "key": "BAR",
            "value": "Bar is bad, really bad"
        }
    ]
}

function getValueForKey(key) {
  var prop = data.prop.filter(function(prop) { return prop.key === key})[0];
  return prop ? prop.value : "unknown key: " + key;
}

document.write(getValueForKey("FOO") + "<br/>");
document.write(getValueForKey("BAR") + "<br/>");
document.write(getValueForKey("FOOBAR"));
&#13;
&#13;
&#13;

普通javascript (使用find,目前主要使用polyfill)

&#13;
&#13;
var data = {
    "prop": [
        {
            "key": "FOO",
            "value": "Foo is wonderfull, foo is great"
        },
        {
            "key": "BAR",
            "value": "Bar is bad, really bad"
        }
    ]
}

function getValueForKey(key) {
  var prop = data.prop.find(function(prop) { return prop.key === key });
  return prop ? prop.value : "unknown key: " + key;
}

document.write(getValueForKey("FOO") + "<br/>");
document.write(getValueForKey("BAR") + "<br/>");
document.write(getValueForKey("FOOBAR"));
&#13;
<script>
// polyfill from https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find#Polyfill
if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}
</script>
&#13;
&#13;
&#13;

普通javascript (使用旧学校for循环)

&#13;
&#13;
var data = {
    "prop": [
        {
            "key": "FOO",
            "value": "Foo is wonderfull, foo is great"
        },
        {
            "key": "BAR",
            "value": "Bar is bad, really bad"
        }
    ]
}

function getValueForKey(key) {
  for (var i = 0; i < data.prop.length; i++) {
    if (data.prop[i].key === key) {
      return data.prop[i].value;
    }
    return "unknown key: " + key;
  }
}

document.write(getValueForKey("FOO") + "<br/>");
document.write(getValueForKey("BAR") + "<br/>");
document.write(getValueForKey("FOOBAR"));
&#13;
&#13;
&#13;

答案 6 :(得分:-1)

您可以使用Array#some并在找到值时结束迭代。

&#13;
&#13;
function getValue(array, key) {
    var value;
    array.some(function (a) {
        if (a.key === key) {
            value = a.value;
            return true;
        }
    });
    return value;
}

var object = { "prop": [{ "key": "FOO", "value": "Foo is wonderfull, foo is great" }, { "key": "BAR", "value": "Bar is bad, really bad" }] };

console.log(getValue(object.prop, 'BAR'));
&#13;
&#13;
&#13;

ES6与Array#find

&#13;
&#13;
function getValue(array, key) {
    return (array.find(a => a.key === key) || {}).value;
}

var object = { "prop": [{ "key": "FOO", "value": "Foo is wonderfull, foo is great" }, { "key": "BAR", "value": "Bar is bad, really bad" }] };

console.log(getValue(object.prop, 'BAR'));
&#13;
&#13;
&#13;