Home > Blockchain >  How do you refer to an object within an object using index positions? Javascript
How do you refer to an object within an object using index positions? Javascript

Time:04-21

Say I have some objects like what's shown below. What I want to do is refer to the index positions in myObjects. For example, myObjects[0].parameter1 would be give me blue. However referencing stuff by index positions doesn't seem to work in objects. Am I just getting the syntax wrong or is this just not possible with javascript?

let myObjects= {
     objectA:{
         parameter1: blue,
         parameter2: 5,
     },
     object B:{
         parameter1: orange,
         parameter2: 4,
     },
}

CodePudding user response:

@raypenbar -- Sorry, i didnt notice you constructed the objects wrong, heres how you should do it.

let myObjects = [
    {
      parameter1: 'blue',
      parameter2: 5,
    },
    {
      parameter1: 'orange',
      parameter2: 4,
    },
  ]

  let obj = myObjects.find(o => o.parameter1 === 'blue');
  console.log(obj)

I also included how you can find that object with a specific parameter, in this case blue and then return it to a variable. Obviously im just console logging the object, but you can use it for whatever you want.

CodePudding user response:

I would highly suggest you make an array instead holding objects..

let myObjects = [

     objectA:{
         parameter1: blue,
         parameter2: 5,
     },
     object B:{
         parameter1: orange,
         parameter2: 4,
     },
]

Then try again with finding by index.

  • Related