Home > Blockchain >  I can't get the object value that i want
I can't get the object value that i want

Time:11-10

Cart {
  items: {
    '618530ebdf45a7e949f085ef': { item: [Object], qty: 1, price: '50' }
  },
  totalQty: 1,
  totalPrice: 50,
  add: [Function (anonymous)],
  reduceByOne: [Function (anonymous)],
  removeItem: [Function (anonymous)],
  generateArray: [Function (anonymous)]
}

I want here to reach the data that in cart.items.item._id but it returned undefined.

  '61879cc4978daa8f84a779c4': {
    item: {
      _id: '61879cc4978daa8f84a779c4',
      name: 'Emre',
      description: 'Doe',
      price: '77',
      color: [Array],
      stok: '88',
      sales: '0',
      img: 'e23cae42dcac7a435ec5e5586e3522c4.jpg',
      category: [Array],
      createdAt: '2021-11-07T09:30:44.862Z',
      slug: 'emre',
      __v: 0
    },
    qty: 1,
    price: '77'
  }

I can reach here as you see with the command that i wrote the following line but could not reach _id.

console.log(cart.items)

CodePudding user response:

cart.items.item is not valid. Your items is an object, that has a key '618530ebdf45a7e949f085ef', so you would need to do something like -

cart.items['618530ebdf45a7e949f085ef'].item._id

const cart = {
  items: {
    '618530ebdf45a7e949f085ef': { item: {_id: '123456'}, qty: 1, price: '50' }
  },
  totalQty: 1,
  totalPrice: 50,
 
}

console.log(cart.items['618530ebdf45a7e949f085ef'].item._id)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Try: console.log(Object.keys(this.cart.items)[0]);

Output: 618530ebdf45a7e949f085ef

Explanation: https://www.javascripttutorial.net/object/convert-an-object-to-an-array-in-javascript/

CodePudding user response:

I believe you are missing the link between items and item

To access what you are looking for you should reach that data via, cart.items['61879cc4978daa8f84a779c4'].item._id

CodePudding user response:

First, I don't know your variable name, so "cart" could be the wrong variable to be selecting the properties from.

Second, You're using the item ID as a property name, so it would be impossible to get the ID, unless you know the ID itself.

I want to help as much as possible, but you haven't posted much code in your question, so I can't really see the problem.

'61879cc4978daa8f84a779c4': {// < Need to get the ID before getting the ID
    item: {
      _id: '61879cc4978daa8f84a779c4',
      name: 'Emre',
      description: 'Doe',
      price: '77',
      color: [Array],
      stok: '88',
      sales: '0',
      img: 'e23cae42dcac7a435ec5e5586e3522c4.jpg',
      category: [Array],
      createdAt: '2021-11-07T09:30:44.862Z',
      slug: 'emre',
      __v: 0
    },
    qty: 1,
    price: '77'
  }
  • Related