嵌套复杂JSON中的搜索键

tpgth1q7  于 2023-04-08  发布在  其他
关注(0)|答案(7)|浏览(135)

我必须通过JavaScript或jQuery在嵌套的JSON中搜索一个键。在我的JSON对象中,所有的键都是唯一的。我自己尝试了一些解决方案,但它们不起作用。下面是我的代码:

json = {
    "app": [{
        "Garden": {
            "Flowers": {
                "Red flower": "Rose",
                "White Flower": "Jasmine",
                "Yellow Flower": "Marigold"
            }
        },
        "Fruits": {
            "Yellow fruit 1": "Mango",
            "Green fruit 2": "Guava",
            "White Flower 3": "groovy"
        },
        "Trees": {
            "label": {
                "Yellow fruit 2": [{"type a":"Pumpkin", "type b": "Banana",..}],
                "White Flower 2": ["Bogan 1", "Bogan 2", ...] 
            }
        }],...
    }

如何在给定对象中搜索特定键?
如果我传递lookup(json, "type a"),它应该返回"Pumpkin",或者如果我搜索"White Flower 2",它应该返回["Bogan 1", "Bogan 2", ...]
以下是我的尝试,它不起作用:

function lookup(obj, k){
    for (key in obj){
        value = obj[key];
        if (k == key) return [k, value];
        if (type(value) == "Object"){
            var y = lookup(value, k);
            if (y && y[0]== k)return y;
        }
        if(type(value) == "Array"){
            for (i in value)
            {
                var x = lookup(value[i], k);
                if (x && x[0]== k)return x; 
            }
        }
        console.log(key, value);
        return null;
    } 
}

为了找到对象的类型,我使用以下代码:

function type(object){
    var stringConstructor = "test".constructor;
    var arrayConstructor = [].constructor;
    var objectConstructor = {}.constructor;

    if (object === null) {
        return "null";
    }
    else if (object === undefined) {
        return "undefined";
    }
    else if (object.constructor === stringConstructor) {
        return "String";
    }
    else if (object.constructor === arrayConstructor) {
        return "Array";
    }
    else if (object.constructor === objectConstructor) {
        return "Object";
    }
    else {
        return "null";
    }
}
vc6uscn9

vc6uscn91#

你比你想象的更接近-把return null;移出for (key in obj)是主要的事情;否则,只要对象中的 first 键不匹配,你就放弃了。只有在搜索完所有键后才给予。

function lookup(obj, k) {
  for (var key in obj) {
    var value = obj[key];

    if (k == key) {
      return [k, value];
    }

    if (typeof(value) === "object" && !Array.isArray(value)) {
      var y = lookup(value, k);
      if (y && y[0] == k) return y;
    }
    if (Array.isArray(value)) {
      // for..in doesn't work the way you want on arrays in some browsers
      //
      for (var i = 0; i < value.length; ++i) {
        var x = lookup(value[i], k);
        if (x && x[0] == k) return x;
      }
    }
  }

  return null;
}

var json = {
  "app": [{
    "Garden": {
      "Flowers": {
        "Red flower": "Rose",
        "White Flower": "Jasmine",
        "Yellow Flower": "Marigold"
      }
    },
    "Fruits": {
      "Yellow fruit 1": "Mango",
      "Green fruit 2": "Guava",
      "White Flower 3": "groovy"
    },
    "Trees": {
      "label": {
        "Yellow fruit 2": [{
          "type a": "Pumpkin",
          "type b": "Banana"
        }],
        "White Flower 2": ["Bogan 1", "Bogan 2"]
      }
    }
  }]
}

function type(object) {
  var stringConstructor = "test".constructor;
  var arrayConstructor = [].constructor;
  var objectConstructor = {}.constructor;

  if (object === null) {
    return "null";
  } else if (object === undefined) {
    return "undefined";
  } else if (object.constructor === stringConstructor) {
    return "String";
  } else if (object.constructor === arrayConstructor) {
    return "Array";
  } else if (object.constructor === objectConstructor) {
    return "Object";
  } else {
    return "null";
  }
}

console.log(lookup(json, 'type a'));
console.log( lookup(json, 'White Flower 2') );
  • p.s.没有所谓的“JSON对象”。如果它不是字符串,它就不是JSON。你正在搜索JavaScript对象。*
yvt65v4c

yvt65v4c2#

function lookup(obj, k) {
  if(typeof(obj) != 'object') {
    return null;
  }
  var result = null;
  if(obj.hasOwnProperty(k)) {
    return obj[k];
  } else {
    for(var o in obj) {
      result = lookup(obj[o], k);
      if(result == null) continue;
      else break;
    }
  }
  return result;
}
var json = {
  "app": [
    {
      "Garden": {
        "Flowers": {
          "Red flower": "Rose",
          "White Flower": "Jasmine",
          "Yellow Flower": "Marigold"
        }
      },
      "Fruits": {
        "Yellow fruit 1": "Mango",
        "Green fruit 2": "Guava",
        "White Flower 3": "groovy"
      },
      "Trees": {
        "label": {
          "Yellow fruit 2": [{"type a":"Pumpkin", "type b": "Banana"}],
          "White Flower 2": ["Bogan 1", "Bogan 2"] 
        }
      }
    }
  ]
}
var rs = lookup(json,'type a');
console.log(rs);
wkftcu5l

wkftcu5l3#

你可以使用下面的代码--

var yourData = $.map(obj, function(el) { return el });  
    //Searching for the key in stored data
            var result = $.grep(yourData, function (e) {
                return e.key == your_search_key;
            });

它会返回你所有的匹配,你可以访问像result[0]希望这将帮助你。

jum4pzuy

jum4pzuy4#

这是一个递归版本,用ES6编写(但要转换到ES5,您只需将箭头函数替换为普通函数,并将const s替换为var s)。

// We could have just returned null if there was no match, but then it wouldn't work if your data contained null.
const notFound = {};

function lookup(obj, search) {

  // Iterate over the object.
  Object.keys(obj).forEach(key => {

    // If we found the key we're looking for, return the matching value.
    if (key === search) {
      return obj[key];

    // If we've got a nested object, recursively call lookup on it.
    // If this object has the key we're looking for, return the matching value.
    } else if (obj[key].constructor === {}.constructor) {
      const result = lookup(obj[key], search);
      if (result !== notFound) return result;
    }

    // Otherwise just go onto the next iteration.

  });

  // If iterating didn't return any matching keys, return notFound.
  return notFound;

}
wwtsj6pe

wwtsj6pe5#

不优雅,但有趣和表演!

function get(data, key) {
  let str = JSON.stringify(data);
  let r = new RegExp(`${key}":"([^"]{1,})"`);
  
  let res = r.exec(str);
  
  return res && res.pop() || null;
}

var data = {
  "app": [
    {
      "Garden": {
        "Flowers": {
          "Red flower": "Rose",
          "White Flower": "Jasmine",
          "Yellow Flower": "Marigold"
        }
      },
      "Fruits": {
        "Yellow fruit 1": "Mango",
        "Green fruit 2": "Guava",
        "White Flower 3": "groovy"
      },
      "Trees": {
        "label": {
          "Yellow fruit 2": [
            {
              "type a": "Pumpkin",
              "type b": "Banana"
            }
          ],
          "White Flower 2": [
            "Bogan 1",
            "Bogan 2"
          ]
        }
      }
    }
  ]
};
console.log('result', get(data, "type a"));
13z8s7eq

13z8s7eq6#

编辑:问题是问 plain js 还是 jquery,我的答案使用了不同的库。但是我仍然会把它作为参考,因为它是实际问题的干净解决方案。
原始答案

我们使用object-scan来满足我们所有的数据处理需求。一旦你了解了如何使用它,它就很强大,并且很容易维护代码。下面是你如何回答你的问题

// const objectScan = require('object-scan');

const lookup = (data, term) => objectScan(['**'], {
  abort: true,
  rtn: 'value',
  filterFn: ({ property }) => property === term
})(data);

const json = { app: [{ Garden: { Flowers: { 'Red flower': 'Rose', 'White Flower': 'Jasmine', 'Yellow Flower': 'Marigold' } }, Fruits: { 'Yellow fruit 1': 'Mango', 'Green fruit 2': 'Guava', 'White Flower 3': 'groovy' }, Trees: { label: { 'Yellow fruit 2': [{ 'type a': 'Pumpkin', 'type b': 'Banana' }], 'White Flower 2': ['Bogan 1', 'Bogan 2'] } } }] };

console.log(lookup(json, "type a"));
// => Pumpkin
console.log(lookup(json, "White Flower 2"));
// => [ 'Bogan 1', 'Bogan 2' ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>
but5z9lq

but5z9lq7#

*//你可以用这段代码来获取对象key-value的数组,其中key //和它的值其中Data是一个Json对象,key是你要搜索的Key//

function lookup(obj,k){ let values = [];
public int findDuplicate(int findDuplicate){int findDuplicate [];

if (k == key)
    {
      values.push({key,value});
    }

    if (typeof value === "object" && !Array.isArray(value)) {
      var y = lookup(value, k);
      // values.push(y);
     values=  values.concat(y);
    }
    if (Array.isArray(value)) {
      // for..in doesn't work the way you want on arrays in some browsers
      //
      for (var i = 0; i < value.length; ++i) {
        var x = lookup(value[i], k);
        
        values=  values.concat(x);
      }
    }
  }

  return values;
}
console.log( lookup(Data, 'key') );

相关问题