在json树节点js中搜索

时间:2015-11-01 11:55:45

标签: javascript search

我有一个json对象。我需要找到yes = 1的字符串并获取有关它的信息(name,yes ....)。如何在节点js中执行此操作?

{"1": {"name":'alex',
      "yes":'1'},
"2": {"name":'andy',
      "yes":'0'}}

或者有没有办法在像mysql这样的对象中进行搜索?

2 个答案:

答案 0 :(得分:0)

如果你想要vanilla javascript,下面也应该适用于node.js

var testObj = {
  "1": {
    "name":'alex',
    "yes":'1'
  },
  "2": {
    "name":'andy',
    "yes":'0'
  }, 
  "3": {
    "name": 'bvvpp',
    "yes": '1'
  }
};

function covertCheckFunc(checker) {
  return function convertChecker(target) {
    var key;
    for (key in checker) {
      if (!target.hasOwnProperty(key)) {
        continue;
      }
      // Single level
      if (typeof target[key] === 'undefined' ||
          target[key] !== checker[key]) {
        return false;
      }
    }

    return true;
  }
}

// Get the first matched item. Return `null` if none match.
function getFirstMatch(checkObj, checker) {
  
  // Convert a object to match to a match function.
  if (Object.prototype.toString.call(checker) !== '[object Function]') {
    checker = covertCheckFunc(checker);
  }

  var key;
  for (key in checkObj) {
    if (checkObj.hasOwnProperty(key) && 
        checker(checkObj[key])) {
      return checkObj[key];
    }
  }

  return null;
}

// Get array of matched item. Return empty array if none match.
function getArrayMatch(checkObj, checker) {
  if (Object.prototype.toString.call(checker) !== '[object Function]') {
    checker = covertCheckFunc(checker);
  }
  var keys = Object.keys(checkObj);
  var arrayForm = keys.map(function(key) {
    return checkObj[key];
  });

  return arrayForm.filter(checker);;
}

console.log(getFirstMatch(testObj, {"yes": '1'}));
console.log(getArrayMatch(testObj, {"yes": '1'}));

如果你接受一些像Underscorelodash这样的库,它可以更简单:

var testObj = {
  "1": {
    "name":'alex',
    "yes":'1'
  },
  "2": {
    "name":'andy',
    "yes":'0'
  }, 
  "3": {
    "name": 'bvvpp',
    "yes": '1'
  }
};

var condition = {
  "yes": '1'
};

var firstMatch = _.findWhere(testObj, condition);
var arrayMatch = _.filter(testObj, function(item) {
  return _.isMatch(item, condition);
});

console.log(firstMatch);
console.log(arrayMatch);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

答案 1 :(得分:0)

假设您只想检查相同级别的属性(即没有您想要递归搜索的嵌套对象),您可以使用简单的for-in循环并直接检查属性值。

var obj = {
           "1": { 
                  "name":'alex',
                  "yes":'1'
                },
           "2": {
                  "name":'andy',
                  "yes":'0'
                }
          };

var results = {};

for (var key in obj) {
    if (obj.hasOwnProperty(key) && obj[key].yes === "1"){
        results[key] = obj[key];
    }
}

console.log(results); // {"1": { "name": "alex", "yes": "1" }}