返回JavaScript对象中的值的路径 [英] Return path to value in JavaScript object

查看:69
本文介绍了返回JavaScript对象中的值的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将给定对象中的绝对路径返回到特定值。

I want to return the absolute path in a given object to a specific value.

以下

A {
  a:1,
  b:2,
  c: {
    1:d,
    2:e
  }
  }

我想抓住'e'并将其作为'Ac'返回2'(或使用JavaScript得到这一点的任何其他格式)。

I want to grab 'e' and return it as 'A.c.2' (or any other format that gets this point across using JavaScript).

我不确定是否应首先对该对象进行字符串化。

I'm not sure whether I should first stringify the object or not.

基本上我只是搜索给定值'searchobj(val)'并尝试返回可以找到相应值以供以后使用的每个路径。

Essentially I'm just searching for given values 'searchobj(val)' and attempting to return each path where the corresponding value can be found for later use.

请不要Jquery。

推荐答案

这是我做的一个递归函数,它搜索对象和将路径返回为abc

Here's a recursive function I made, that searches through the object and return the path as a.b.c

var obj = {
   "a": {
      "b": {
         "c": {
            1: 6
         }
      }
   },
   "d": {
      "e": 7
   },
   "h": {
      "g": 7
   },
   "arr": {
      "t": [22, 23, 24, 6]
   }

};

这将返回匹配为字符串的第一个路径。

This will return the first path that is matched as a string.

var getObjectPath = function(search, obj) {

    var res = false;

    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (typeof obj[key] == "object") { //If value is an object, call getObjectPath again!
                if (res = getObjectPath(search, obj[key])) {
                    res = key + "." + res;
                    return res; 
                }
            } else if (search === obj[key]) {
                return key; //Value found!
            }
        }
    }

    return res;
}
console.log(getObjectPath(7, obj)); //d.e
console.log(getObjectPath(6, obj)); //a.b.c.1
console.log(getObjectPath(24, obj)); //arr.t.2 //2 is the index

多个匹配搜索,将返回一个数组路径

Multiple matches search, will return an array of paths

var getObjectPathMultiple = function(search, obj, recursion) {

    var res = false;
    var paths = [];

    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (typeof obj[key] == "object") {
                if (res = getObjectPathMultiple(search, obj[key], true)) {
                    res = key + "." + res;
                    if (!recursion)
                        paths.push(res);
                    else return res;
                }
            } else if (search === obj[key]) {
                return key;
            }
        }
    }
    return recursion ? res : paths;
}
console.log(getObjectPathMultiple(7, obj)); //["d.e", "h.g"]
console.log(getObjectPathMultiple(6, obj)); //["a.b.c.1", "arr.t.3"]
console.log(getObjectPathMultiple(24, obj)); //["arr.t.2"]

这篇关于返回JavaScript对象中的值的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆