2015-12-22 52 views
0

我有一个对象,它看起来是这样的:其子获取父在对象结构

{ 
"11": { 
    "id": 11, 
    "parent_product": 0, 
    "product_name": "WebStore", 
    "product_price_city": null, 
    "child": { 
     "12": { 
     "id": 12, 
     "parent_product": 11, 
     "product_name": "WebStore - Single", 
     "product_price_city": 500 
     }, 
     "13": { 
     "id": 13, 
     "parent_product": 11, 
     "product_name": "WebStore - Full", 
     "product_price_city": 2500 
     } 
    } 
    } 
} 

这里,关键11有两个孩子的:1213

在不同的对象,看起来像这样:

{ 
    "316": 
    { 
     "id": 316, 
     "product_id": 13, 
     "sold_by": 1, 
     "product_price": 5000, 
     "subscription_month": 3, 
     "updated_by": 0, 
     "created_at": 1449573556 
    }, 
    "317": 
    { 
     "id": 317, 
     "product_id": 12, 
     "sold_by": 1, 
     "product_price": 5000, 
     "subscription_month": 3, 
     "updated_by": 0, 
     "created_at": 1449573556 
    } 
} 

我这里的product_id是12或13,也就是它永远是个孩子。

我需要获得12和13的父ID,所以我可以访问他们的第一个对象。

data.11 

如何在JavaScript中获得它?

+0

你可以改变数据是如何组织/结构化或为这最后? – AlvaHenrik

+0

每个孩子只有一个家长吗? –

+0

@阿米尔:是的。每个孩子只有一个父母。 – nirvair

回答

3

只需获取属性并遍历它即可。

var object1 = { 
 
     "11": { "id": 11, "parent_product": 0, "product_name": "WebStore", "product_price_city": null, "child": { "12": { "id": 12, "parent_product": 11, "product_name": "WebStore - Single", "product_price_city": 500 }, 
 
     "13": { "id": 13, "parent_product": 11, "product_name": "WebStore - Full", "product_price_city": 2500 } } }, 
 
     "15": { "id": 15, "parent_product": 0, "product_name": "WebStore", "product_price_city": null, "child": undefined }, 
 
     "17": { "id": 17, "parent_product": 0, "product_name": "WebStore", "product_price_city": null } 
 
    }, 
 
    key; 
 

 
function getParent(id, object) { 
 
    var k; 
 
    Object.keys(object).some(function (a) { 
 
     if (object[a].child && id in object[a].child) { 
 
      k = a; 
 
      return true; 
 
     } 
 
    }); 
 
    return k; 
 
} 
 

 
document.write(getParent('12', object1) + '<br>'); // '11' 
 
key = getParent('42', object1); 
 
if (typeof key === 'undefined') { 
 
    document.write('no key found'); 
 
}

+1

这个工程!谢谢。 – nirvair

+0

有一个问题。有些情况下父母没有孩子。在这种情况下应该做什么? – nirvair

+1

在if子句中添加一个测试if(object [a] .child && ...',就像上面那样。 –