在变量中搜索值... Javascript

时间:2014-12-17 14:55:30

标签: javascript variables find

我找不到怎么做...... ?(在块var [javascript]中查找变量!)? 我希望能从这里找到让尼古拉斯·菲利普斯说的话......

var profiles = {
    Nicholas_Phillips: {
        Name: "Nicholas_Phillips"
    }
}

然后得到变量部分“profiles.Nicholas_Phillips”或我猜的父级持有者?!

3 个答案:

答案 0 :(得分:0)

您只需递归搜索对象:

function search( obj, needle, path ) {

  // get all keys from current object
  var keys = Object.keys( obj );

  // walk all properties
  for( var i=0; i<keys.length; i++ ) {

    // check for a match
    if( obj[ keys[i] ] === needle ) {
       return path + '.' + keys[i];
    }

    // if it is a subject, search it recursively
    if( typeof obj[ keys[i] ] == 'object' ) {
      var recCall = search( obj[ keys[i] ], needle, path + '.' + keys[i] );

      // if we had a match, return it
      if( recCall !== null ) {
        return recCall;
      }
    }
  }

  // if we came this far, no match was found
  return null;
}

// execute
var path = search( profiles, "Nicholas_Phillips", 'profiles' );

我不确定,您想要搜索的内容(值或键?)以及返回的内容(路径或对父级的引用?),但上述代码应适用于所有进行一些细微更改。< / p>

答案 1 :(得分:0)

你需要一个递归搜索,有些模糊:

var profiles = {
  Nicholas_Phillips: {
    Name: "Nicholas_Phillips"
  }
};
function find(obj, value, path) {
  if (Object.keys(obj).some(function(key) {
      var thisValue = obj[key];
      var p;
      if (thisValue === value) {
        // Found it, set the path and return true to stop looping (true = stops `some`)
        path = path ? path + "." + key : key;
        return true;
      }
      if (typeof thisValue === "object") {
        // Found an object, recurse into it
        p = find(thisValue, value, path ? path + "." + key : key);
        if (p) {
          // We found it (somewhere) in that object, set the path and stop looping
          path = p;
          return true;
        }
      }
    })) {
    // We found it, return path
    return path;
  }
  // Not found, return undefined
  return undefined;
}
snippet.log(find(profiles, "Nicholas_Phillips")); // "Nicholas_Phillips.Name"
snippet.log(find(profiles, "foo")); // undefined
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

find的实现返回它找到的属性的路径。 进行了广泛的测试,但它应该指出正确的方法。

答案 2 :(得分:-1)

这是一个快速函数,它包含您要搜索的对象,我们要搜索的子对象以及我们想要从该子对象获取的值。然后它会查看对象中的所有键,看看它们是否与您的值相匹配。如果有,它还确保该特定对象(而不是其原型)具有密钥。然后它检查子对象是否具有所需的值,并返回该值。

   function findKey(obj, child, value){
       for (key in obj) {
         if (key === child && obj.hasOwnProperty(child)){
             if(obj[child][value]){
                     return obj[child][value]
                  }
          }
      }
    }

因此,如果我们在你的问题的上下文中运行它:

findKey(profiles, "Nicholas_Phillips", "Name");

它将返回

"Nicholas_Phillips"

否则会返回undefined