简体   繁体   中英

How to get the name from the array in javascript?

I am fairly new to JavaScript and I am trying to extract the name Sam from the array. The output that I'm getting is name. How do I get Sam? Thank you in advance. I apologize but I know this is a fairly novice question.

I am trying to loop by using forEach.

let Person = {
  name: ['Sam']
}

let handler = Object.keys(Person)

handler.forEach(function(element){
  console.log(element)
})

 let Person = { name: ['Sam'] } for (const fn of ["values", "keys", "entries"]) { console.log(`Using: Object.${fn}()`); for (const v of Object[fn](Person)) { console.log(v); } } 

代替Object.keys使用Object.values

If you know in advance that your name array is located under the key name , then access it directly

 const person = { name: ['Sam'] }; console.log(person.name); console.log(person.name[0]); 

Otherwise, use Object.values() to enumerate the values in the object, but you might get more values than simply the names array and you will have to find out which value contains the names you are looking for:

 const person = { name: ['Sam'], anotherProp: 'hello' }; console.log(Object.values(person)); 

Using Object.entries() is not helpful in this situation as if you use it, it means that you know under which property is located your name array, and if this is the case, simply access the array directly.

If you use Object.keys() you can get the value by using object[key] bracket notation or object.key dot notation.

Object.keys(obj).forEach(key => obj[key]);

 let Person = { name: ['Sam'] } Object.keys(Person).forEach(name => console.log(`${name} = ${Person[name]}`)); 

 let Person = { name: ['Sam',"Bob","Alice"] } let count = Person.name.length; for(let i = 0; i<count; i++){ console.log( Person.name[i]) } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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