[英]Get parent from its child in object structure
I have an object which looks something like this: 我有一个看起来像这样的对象:
{
"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
}
}
}
}
Here, the key 11
has two childs: 12
and 13
. 此处,键
11
有两个子代: 12
和13
。
In a different object which looks like this: 在另一个看起来像这样的对象中:
{
"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
}
}
I here the product_id is either 12 or 13, that is it will always be a child. 我在这里product_id是12或13,也就是说它将永远是孩子。
I need to get the parent id of 12 and 13, so I can access they the first object. 我需要获取父ID为12和13,这样我才能访问它们的第一个对象。
data.11
How can I get it in JavaScript? 如何在JavaScript中获得它?
Just get the properties and iterate over it. 只需获取属性并对其进行迭代即可。
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.