[英]Get parent from its child in object structure
我有一個看起來像這樣的對象:
{
"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
有兩個子代: 12
和13
。
在另一個看起來像這樣的對象中:
{
"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,也就是說它將永遠是孩子。
我需要獲取父ID為12和13,這樣我才能訪問它們的第一個對象。
data.11
如何在JavaScript中獲得它?
只需獲取屬性並對其進行迭代即可。
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'); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.