2016-11-22 39 views
1
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),我还需要该对象位于“男性”&“people”中,而不仅仅是数字中的所有内容。

我可以使用类似的函数来获取read()以获得“数字之后的任何内容”(因此,如果存在名称和项目,我会记住以前的键)。

+0

请添加相关的缺码,以及和输入的一些例子,想要输出,也许你看看这里:[MCVE] –

+0

@NinaScholz有无漏码?我添加了'read(locations)',并将坐标改为数字,'spot'功能改为'console.log'以供您欣赏 - 但代码完全一样。 – user1768788

+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);