0

I am not sure how to get the nested object data in react jsx, can anyone help me?

wine:
{
_id: "5b21ca3eeb7f6fbccd471815",
name: "Margaux",
wineType: { _id: "5b21ca3eeb7f6fbccd471818", name: "Red Wine" },
numberInStock: 5,
vintage: 1982,
volume: 750,
imageURL:
  "www.abc.come",
region: { _id: "2", name: "Bordeaux" },
price: 18000
},

I am looking for the name in region object,

I try testing {wine.region.name} but having error.

TypeError: Cannot read property 'name' of undefined
5
  • 2
    I think it need to be variableName.Wine.region.name Commented Oct 25, 2018 at 10:32
  • In json you have defined Wine but you are accessing it will small letter {wine.region.name} Commented Oct 25, 2018 at 10:32
  • Put this object into an variable and then access using that variable. Commented Oct 25, 2018 at 10:33
  • may be its rendering issue means you are accessing data before initializing of object. Commented Oct 25, 2018 at 10:34
  • I can actually get data with {wine.name} and result in "Margaux", Commented Oct 25, 2018 at 10:37

3 Answers 3

1

U have to use the object as invariable so define let data = {....} or in JSON file { "data": {....} ,...}.

let wine={
        _id: "5b21ca3eeb7f6fbccd471815",
        name: "Margaux",
        wineType: { _id: "5b21ca3eeb7f6fbccd471818", name: "Red Wine" },
        numberInStock: 5,
        vintage: 1982,
        volume: 750,
        imageURL:
          "www.abc.come",
        region: { _id: "2", name: "Bordeaux" },
        price: 18000
    }

    let {region:{name}}=wine;
    console.log('name',name);

O/P : Bordeaux

Sign up to request clarification or add additional context in comments.

Comments

1

Your format of json is not looking correct please try this one

wine={
    _id: "5b21ca3eeb7f6fbccd471815",
    name: "Margaux",
    wineType: { _id: "5b21ca3eeb7f6fbccd471818", name: "Red Wine" },
    numberInStock: 5,
    vintage: 1982,
    volume: 750,
    imageURL:
      "www.abc.come",
    region: { _id: "2", name: "Bordeaux" },
    price: 18000
}

first assign the hole object in wine and then try to access like {wine.region.name} it will work. It seems like a wrong format of json.

Comments

1

As you can see in the attachment your JSON is not valid and running it as it is throws error of invalid token thats why you are unable to go to the next nodes. The attachment also shows how to correctly use it and visit specific node in jason[1]: https://i.sstatic.net/xsVcU.png

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.