还记得以前的密钥吗?

时间:2016-11-22 13:50:36

标签: javascript dictionary

function read(a) {
    var key = Object.keys(a)[0];
    if (!key) {
        return {}
    } else if (!key.includes(";")) {
        var inkey = a[key];
        delete a[key]
        return read(Object.assign({}, inkey, a))
    } else {
        console.log(key)
        delete a[key]
        return read(a);
    }
}

var locations = {
    "buildings":{
        "3;":{"name":"Market"},
        "8;":{"name":"Free car"},
        "9;":{"name":"House"}
    },
    "people":{
        "males":{
            "16;":{
                "name":"John",
                "items":{
                    "food":1,
                    "water":1
                }
            }
        }
    }
}
read(locations);

函数read(locations)按预期执行并打印每个数字。

我将如何找到最接近固定数字的内容,包括之前的密钥。

例如:如果与数字最接近的是“John”(数字16),我还需要该对象位于“男性”和“男性”中。 “人”,而不仅仅是“数字”中的所有内容。

我可以使用与read()类似的功能来获取“数字之后”的任何内容(如果它存在则为名称和项目),但我想记住以前的键。

1 个答案:

答案 0 :(得分:0)

您可以为对象的路径添加变量。



function read(a, path) {
    if (!a || typeof a !== 'object') {
        return {};
    }
    Object.keys(a).forEach(function (key) {
        if (key.includes(";")) {
            console.log(key, path.join(', '));
            return read(a[key], path || []);
        }
        read(a[key], (path || []).concat(key));
    });
}

var locations = { buildings: { "3;": { name: "Market" }, "8;": { name: "Free car" }, "9;": { name: "House" } }, people: { males: { "16;": { name: "John", items: { food: 1, water: 1 } } } } };

read(locations);




相关问题