P.S. Perumal
P.S. Perumal

Reputation: 11

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 i.e 10 (object1 value)

Upvotes: 1

Views: 51

Answers (1)

Martin Heralecký
Martin Heralecký

Reputation: 5779

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)
})

Upvotes: 3

Related Questions