简体   繁体   中英

to get a value from an array in node js

const psp=[
  object1="10",
  object2="20"
]
psps.post(psp)
psps.forEach(psp1=>{
  console.log(psp1.object1)
})

While I'm running this code I'm getting undefined value on my terminal I like to get an output ie 10 (object1 value)

psp in an array and arrays don't have keys. Objects do:

const psp = {     // curly braces for object definition
  object1: "10",  // colon instead of equal sign
  object2: "20"
}

What actually happens in your code is that psp resolves to an array containing two strings "10" and "20" , because object1="10" resolves to the assigned value. However, if you meant this to be an object with object1 and object2 to be its keys, you need to use curly braces to define an object and a colon between keys and values, as mentioned above.

If you don't need the keys and indeed intended to use an array, you can do so like this:

const psp = [
  "10",
  "20"
]
psps.push(psp)

psps.forEach(psp1 => {
  console.log(psp1)
})

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