简体   繁体   English

如何在对象/数组内链接?

[英]How do I link within an object/array?

I want to link users with their parents/children/spouses in same .js file我想在同一个 .js 文件中将用户与他们的父母/孩子/配偶联系起来

So, how do I 'link' within an object.那么,我如何在对象中“链接”。 Let say:让说:

const users = {
  bradpitt: {
    name: "Brad",
    lastname: "Pitt",
    spouses: [{
      angelinajolie
    }]
  },
  angelinajolie: {
    name: "Angelina",
    lastname: "Jolie",
    parents: [{
      jonvoight
    }]
  }
  jonvoight: {
    name: "Jon"
  }
}

So I can use it like this:所以我可以这样使用它:

getParents() {
  for (const u of users) {
    return u.parents.name
  }
}

Result: Jon结果:乔恩

You are on the right way, but missing some key features:您走在正确的道路上,但缺少一些关键功能:

Take a look at the comments within this snippet!看看这个片段中的评论!

The main problem is the fact that you assign the object angelinajolie to bradpitt before the object angelinejolie is defined.主要问题是您在定义对象angelinejolie之前将对象angelinajolie分配给bradpitt An easier and more secure way to do this is with id's because names are not unique.一种更简单、更安全的方法是使用id's因为名称不是唯一的。 I've used this in my example:我在我的例子中使用了这个:

Also with properties you use a for...in loop and you need to check if the property is available.同样对于属性,您使用for...in循环,您需要检查该属性是否可用。 If u.parents is undefined it will throw an error.如果u.parents undefined ,则会抛出错误。

I've changed the unique names to id numbers build with the string id and six digits.我已将唯一名称更改为使用字符串id和六位数字构建的 id 编号。 id00000 . id00000 In the users object I simply refer to the user without the leading zeros and id.在用户对象中,我只引用没有前导零和 id 的用户。 To rebuild this in the getParents function I've used String.prototype.padStart .为了在getParents函数中重建它,我使用了String.prototype.padStart It pads zeros to the left of the string until 6 characters are reached.它在字符串的左侧填充零,直到达到 6 个字符。

"id"+(p.toString().padStart(6, '0'));

 const users = { id000001 : { name: "Brad", lastname: "Pitt", spouses: [ 1 ] }, id000002 : { name: "Angelina", lastname: "Jolie", parents: [ 3 ] }, //fixed a missing comma here id000003: { name: "Jon" } } function getParents() { //define a return object //return parents per set of users const parents = {}; //iterate over every user for (key in users) { const u = users[key]; //if the user has parents go on if (u.parents) { //save the parents to parent object with the user as key: //use map to iterate over every parent and return the name of the parent parents[key] = u.parents.map((p) => users["id"+(p.toString().padStart(6, '0'))].name); } }; //return the parents object return parents; } //log to console to show results: console.log(getParents());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM