按键查找和检索对象值,包括嵌套对象

时间:2016-09-20 13:54:06

标签: javascript angularjs javascript-objects

我试图在不知道对象的情况下通过value找到key,包含嵌套对象,因此该函数将获取一个键和一个对象并返回值或未定义。 这是我的功能:

/* Iterate over object and include sub objects */

function iterate (obj, key) {

    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            //in case it is an object
            if (typeof obj[property] == "object") {
                if (obj.hasOwnProperty(key)) {
                    return obj[key]; //return the value 
                }
            }
            else {
                iterate(obj[property]);
            }
        }   
    }

    return undefined;
}

我在循环中调用return,因此效率更高(希望如此......)。

1.是否有人准备好此功能?这个不起作用。

2.有人知道要改变什么才能让它发挥作用?

任何帮助,包括angular.js功能都会很棒。

感谢。

3 个答案:

答案 0 :(得分:4)

你稍微扭转了一点,你忘了将第二个参数传递给递归函数调用。此外,在这种情况下,无需返回undefined,因为这是默认值。

function iterate (obj, key) {
    var result;

    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            // in case it is an object
            if (typeof obj[property] === "object") {
                result = iterate(obj[property], key);

                if (typeof result !== "undefined") {
                    return result;
                }
            }
            else if (property === key) {
                return obj[key]; // returns the value
            }
        }   
    }
}

编辑:实际上,在我们要查找值为对象的键的情况下,我们应该检查属性是否等于键,然后检查值是否是可迭代对象。感谢@Catinodeh!

function iterate (obj, key) {
    var result;

    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            if (property === key) {
                return obj[key]; // returns the value
            }
            else if (typeof obj[property] === "object") {
                // in case it is an object
                result = iterate(obj[property], key);

                if (typeof result !== "undefined") {
                    return result;
                }
            }
        }   
    }
}

答案 1 :(得分:1)

首先使用解决此问题的函数取消它: Fastest way to flatten / un-flatten nested JSON objects

然后再次使用public class Cars { private String carID; private String plateNum; private static String position; private static Attendant assignedTo; private long currTime; static String[] tempArray2 = new String[Garage.getCarsCapacity()]; public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) { this.carID = carID; this.plateNum = plateNum; Cars.position = position; Cars.assignedTo = assignedTo; this.currTime = currTime; } private static void createCarsID() { for (int x = 0; x < Garage.getCarsCapacity(); x++) { tempArray2[x] = ("CR" + (x + 1)); } } public static String getID() { createCarsID(); String tempID = null; String tempPos = null; for (int x = 0; x < tempArray2.length; x++) { if (tempArray2[x] != null) { tempID = tempArray2[x]; tempPos = tempArray2[x]; getPos(tempPos); tempArray2[x] = null; break; } } return tempID; } public static void getPos(String IdToPos) { String strPos = IdToPos.substring(2); int pos = Integer.parseInt(strPos); position = "GR" + pos; } public String getPlateNum() { return plateNum; } public String getCarID() { return carID; } public static String getPosition() { return position; } public long getCurrTime() { return currTime; } public static Attendant getAssignedTo() { return assignedTo; } public static String askCarID() { boolean valid = false; System.out.println("Please enter your car's plate number."); Scanner scanCarID = new Scanner(System.in); String scannedCarID = scanCarID.nextLine(); while (!valid) { if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) { valid = true; System.out.println(scannedCarID); } else { System.out.println("Please enter a valid plate number. Ex: AF 378"); askCarID(); } } return scannedCarID.toUpperCase(); } public static String convert(long miliSeconds) { int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24; int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60; int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60; return String.format("%02d:%02d:%02d", hrs, min, sec); } }

答案 2 :(得分:0)

这是一个对我有用的代码段。对我来说,我只搜索没有数组的嵌套对象。

function searcObject(obj, key){
        var found = false
        if(typeof obj == 'object' && obj !== null){
            Object.keys(obj).forEach(function(prop) {
                if(prop == key){
                    value = obj[key];
                    return true;
                } else{
                    searcObject(obj[prop], key);
                }
            });    
        } else {
            return false;
        }; 
    };