如何通过一个属性(在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"]};

现在让我们说,我想表达这样一个事实,即人1是人2的父亲,因此,人2是人1的儿子。也就是说;小查理;在person1的CCD_ 1属性中为person2;查理;在person2的CCD_ 2属性中为person1。

我怎样才能做到这一点?我看不出将一个对象嵌入另一个对象中会如何解决问题,只是简单地复制它。有没有办法将对象中的属性作为另一对象的标识符?

非常感谢!

例如,如果你想知道某人是否是人1的孩子,你可以这样做:

person1.childrenNames.forEach((childrenName) => { 
if(childrenName=== person2.name) {
console.log(person1.name + ' is the parent of + person2.name);
});

你也可以做一个嵌套函数,这样你就可以检查这个人是否是多个人的父母。

为什么不添加关系索引?将您的人员组合为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",
age: 65,
parentNames: ["Dolph", "Grace"]
},
{
name: "Dolph",
age: 65,
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]];
}

我想这取决于您的场景有多复杂以及您想要实现什么,但假设您为relations添加了一个额外的表。该表可以保存两个人共享的关系类型的信息,然后可以用来查找该数据。

例如,如果我们有4个人,其中2个是父母(Charlie&Grace(,1个是儿子(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, name: 'Grace', age: 36 }
],
relations: [
{ id: 1, person1: 1, person2: 2, type: 'spouse', from: 1970, till: null },
{ id: 2, person1: 3, person2: 4, type: 'spouse', from: 2010, till: null },
{ id: 3, person1: 1, person2: 3, type: 'parent' },
{ id: 3, person1: 2, person2: 3, 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的母亲(
  • 识别两个人之间某个CCD_ 5的关系的表

之后,您只需要一种方法从数据集中查找信息,就可以开始

最新更新