如何解决如何通过属性在javascript中关联两个或多个对象?
假设我有两个对象:
let person1 = {name: "Charlie",age: 65,childrenNames:["Ruth","Charlie Jr."] parentNames: ["Dolph","Grace"]};
let person2 = {name: "Charlie Jr.",age: 34,childrenNames:[] parentNames: ["Charlie","Grace"]};
现在,我想表达一个事实,即person1是person2的父亲,因此,person2是person1的儿子。也就是说,person1的childrenNames
属性中的“ Charlie Jr”是person2,person2的parentNames
属性中的“ Charlie”是person1。
我该如何实现?我看不到将一个对象嵌入另一个对象如何解决问题,而只是复制它。有没有一种方法可以使对象内部的属性成为另一个对象的标识符?
非常感谢!
解决方法
例如,如果您想知道某人是否是第1个人的孩子,则可以执行以下操作:
person1.childrenNames.forEach((childrenName) => {
if(childrenName=== person2.name) {
console.log(person1.name + ' is the parent of + person2.name);
});
您还可以执行嵌套函数,以便检查该人是否是多个人的父母。
,我想这取决于场景的复杂程度和想要实现的目标,但是说您为relations
添加了一个额外的表。该表可以保存有关2个人共享的关系类型的信息,然后可以用于查找该数据。
例如,如果我们有4个人,其中2个人是父母(Charlie&Grace),1个人是儿子(Charlie Jr),则我们可以形成如下关系表。
我们不需要指出小查理(Charlie Jr)是儿子,因为我们已经认识了孩子的父母。
const familyDb = {
persons: [
{ id: 1,name: 'Charlie',age: 68 },{ id: 2,name: 'Grace',age: 64 },{ id: 3,name: 'Charlie Jr',age: 34 },{ id: 4,age: 36 }
],relations: [
{ id: 1,person1: 1,person2: 2,type: 'spouse',from: 1970,till: null },person1: 3,person2: 4,from: 2010,person2: 3,type: 'parent' },person1: 2,type: 'parent' }
]
};
function getParents( person ) {
return familyDb.relations.filter( relation => relation.person2 === person.id && relation.type === 'parent' );
}
function getChildren( person ) {
return familyDb.relations.filter( relation => relation.person1 === person.id && relation.type === 'parent' );
}
console.log( getParents( familyDb.persons[2] ) );
console.log( getChildren( familyDb.persons[0] ) );
因此,以上代码对此采取了基本的方法,您有:
- 用于标识人物的唯一
id
(在您的示例中,姓名匹配非常困难,因为Grace既是Charlie&Charlie Jr的母亲) - 用于识别两个人之间
type
之间的关系的表
之后,您只需要一种方法即可从数据集中查找信息,就可以开始使用
,为什么不添加关系索引?将您的人员合并为1个人阵列。 迭代并添加parentIndexes而不是parentNames。这样,您不用索引来查找父母或儿子,而是有了索引。
注意,为使我的示例简单,我仅做父母之间的关系。您可以使用完全相同的逻辑轻松地将儿子添加到父母关系中。
示例
if (peopleArray[i].parentsIndex.length > 0) {
// get first parent
//peopleArray[peopleArray[i].parentsIndex[0]];
}
修改对象。
let peopleArray = [
{
name: "Charlie",age: 65,parentNames: ["Dolph","Grace"]
},{
name: "Grace",{
name: "Dolph",parentNames: ["ADSGS","Grace"]
}
];
peopleArray = peopleArray.map(callback.bind(null));
function callback(item) {
item["parentsIndex"] = [];
for (let i = 0; i < item.parentNames.length; i++) {
let parentObj = peopleArray.find(x => x.name === item.parentNames[i]);
if (parentObj !== undefined) {
item["parentsIndex"].push(peopleArray.indexOf(parentObj));
}
}
return item;
}
console.log(peopleArray);
// use case
if (peopleArray[0].parentsIndex.length > 0) {
// get first parent
//peopleArray[peopleArray[0].parentsIndex[0]];
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。