在某些情况下,一种方法是否优于另一种方法,或者是否存在可接受的“最佳实践”?以下面为例:
project:{
team:{
testers:{
1 : {first: 'employee', last: 'one'},
2 : {first: 'employee', last: 'two'}
},
experts:{
1 : {first: 'employee', last: 'one'},
3 : {first: 'employee', last: 'three'}
}
}
};
employees:{
1 : {first: 'employee', last: 'one'},
2 : {first: 'employee', last: 'two'},
3 : {first: 'employee', last: 'three'}
};
对比
project:{
team:{
testers:[1,2],
experts:[1,3]
}
};
employees:{
1 : {first: 'employee', last: 'one'},
2 : {first: 'employee', last: 'two'},
3 : {first: 'employee', last: 'three'}
};
对比
project:{
team:{
testers:[
{id: 1, first: 'first', last: 'one'},
{id: 2, first: 'employee', last: 'two'}
],
experts:{
{id: 1, first: 'employee', last: 'one'},
{id: 3, first: 'employee', last: 'three'}
}
}
};
employees:[
{id: 1, first: 'employee', last: 'one'},
{id: 2, first: 'employee', last: 'two'},
{id: 3, first: 'employee', last: 'three'}
];
让我们添加一个非常具体的情况。我正在使用结合了多选的 Handlebars 模板。我想创建一个多选列表,列出所有有资格成为专家的员工,同时预选已被确定为项目专家的员工。如果我使用示例 3,我必须执行以下操作来构建我的多选:
for(var x in employees){
var found = 0;
for(var y in project.team.experts){
if(project.team.experts.[y] === employees[x].id){
found = 1;
}
}
if(found){
//Print selected option
} else {
//Print unselected option
}
}
但是,如果我使用示例 1:
for(var x in employees){
if(typeof project.team.experts[employees[x].id] !== 'undefined'){
//Print selected option
} else {
//Print unselected option
}
}
最佳答案
我相信这取决于您将使用这些对象做什么。
您可以使用 (json) 对象发送到 API、提供模板、在对象之间进行通信、根据需要提取值等...
格式的主要内容是:
employees:{
1 : {first: 'employee', last: 'one'},
2 : {first: 'employee', last: 'two'},
3 : {first: 'employee', last: 'three'}
};
采用以下格式更有意义:
employees: [{id: 1, name: "John"}, {id: 2, name: "Kim"}];
因为员工是对象的集合(数组)而不是单个对象。
这将使您更轻松地提取数据或对对象执行操作。
我不确定 first
和 last
参数的含义,但我认为使对象属性具有描述性也是一个好主意(让它们清楚名称)。
但我认为这非常取决于具体情况。
很可能有一天,您需要发送一个以下格式的对象作为 URL 搜索参数,以便符合某个 api 的要求:
{employees: "1, 2, 3"}
关于javascript - 一个对象什么时候应该包含其他对象,什么时候应该引用其他对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27607682/