引用另一个Javascript对象中存在的Javascript对象的最佳方法是什么?例如,根据以下数据,我如何正确引用个人的“主页”,这是对同一数据集中另一个对象(地点)的引用?
var data = {
"people": [{
"name": "Jack",
"age": "8",
"home": data.places[0].country
}, {
"name": "John",
"age": "9",
"home": data.places[1].country
}],
"places": [{
"country": "Holland"
}, {
"country": "Germany"
}]
}
答案 0 :(得分:0)
通常,JSON用作“嵌套”数据格式。因此,不是将关系指针指向其他数据(如关系数据库),而是直接将数据作为子对象插入。实际上,这会导致一些数据重复(非规范化,在数据库方面)。
{
"people": [{
"name": "Jack",
"age": "8",
"home": "Holland"
}, {
"name": "John",
"age": "9",
"home": "Germany"
}],
"places": [{
"country": "Holland"
}, {
"country": "Germany"
}]
}
我在标准JSON中看到的最接近“引用”的是在API中使用它(如在Tastypie中)。在此设置中,引用被编码为API URI,客户端稍后可以使用它来请求数据集的其他位。
{
"people": [{
"name": "Jack",
"age": "8",
"home": "/api/v1/place/1/"
}, {
"name": "John",
"age": "9",
"home": "/api/v1/place/2/"
}]
}
答案 1 :(得分:0)
为什么不像这样重新格式化数据:
var data.places = {
"Holland": {otherinfo},
"Germany": {otherinfo}
};
data.people = [{
"name": "Jack",
"age": "8",
"home": data.places.Holland
}, {
"name": "John",
"age": "9",
"home": data.places.Germany
}];
答案 2 :(得分:0)
我会通过列出所有地方来解决问题,为每个地方分配一个ID。
然后每个人都会简单地引用ID。
var data = {
"people": [{
"name": "Jack",
"age": "8",
"home_id": 0
}, {
"name": "John",
"age": "9",
"home_id": 1
}, {
"name": "Inge",
"age": "11",
"home_id": 0
}],
"places": [{
"id" : 0,
"country": "Holland"
}, {
"id" : 1,
"country": "Germany"
}]
}
答案 3 :(得分:0)
拆分您的声明,以便在您引用data.places时存在。
var data = {
"places": [{
"country": "Holland"
}, {
"country": "Germany"
}]
}
// data is now defined and has the property "places"
data.people = [{
"name": "Jack",
"age": "8",
"home": data.places[0].country // No more error
}, {
"name": "John",
"age": "9",
"home": data.places[1].country // No more error either
}]
在您的问题中,您的对象在完全定义之前就引用了自身的元素。这导致了TypeError: Cannot read property 'places' of undefined
。在我的解决方案中,我拆开了对象定义,以便在定义data.people
时,data.places
件数组已经存在。
不必一次声明对象。