Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

javascript - JS get value of nested key with changing parent name

I need to get the value of roles in the following example.

const obj ={
    id: 1,
    "website.com": {
        roles: ["SuperUser"]
    }
}

const r = obj.hasOwnProperty("roles")
console.log(r)

Its parent objects name ("website.com") can change everytime as Im requesting it from the db. What is the best way to get this variable?

The obj would also be relatively large I just didnt include it in the example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could iterate over the object and exclude id. Example:

for (var x in obj) {
  if (x !== 'id') {
    console.log(obj[x].roles)
  }
}

EDIT (to address your question edit):

If the root object has many keys, it would probably make sense to instead either move the domain from a key to a value (for example, domain: 'website.com' and move the roles up (flattening the object); or you could check for a key that looks like a domain using a regex. Example: if (/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:.[a-zA-Z]{2,})+$/.test(x) rather than if (x !== 'id'). The regex way would probably be brittle.

EDIT 2:

You could use the hasOwnProperty check like this:

let roles
for (let x in obj) {
  if (obj[x].hasOwnProperty(roles)) {
    roles = obj[x])
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...