deeej
deeej

Reputation: 387

How do I loop JSON and output value?

I have some JSON being returned from an api like this:

callback({"Message":"","Names”:[{“id”:”16359506819","Status":"0000000002","IsCurrent":true,"Name":"JAKE","NameType”:”Small,”Postcode”:”2000”,”Score":100,"State”:”NSW”}]})

Vuejs Method

methods: {
    getResults() {
      // sent a GET request
      axios.get("https://myapi" + this.searchvalue +"&maxResults=10&guid=" + this.guidId).then((response) => {
        if(response.status===200){
            if(response.data){
                console.log(response.data);

                // need to console log name for each item
                // console.log("Name :" + response.data.Names.Name)
            }
            else{
                //do nothing 
                }   
        }
        }).catch(function (error){
            console.log(error);
      });
    },
  },
};

How do I loop through each item and console log the name value?

Upvotes: 0

Views: 160

Answers (1)

hgb123
hgb123

Reputation: 14891

Names is a list of objects, so you could iterate this list and log the property .Name

const data = {
  Message: "",
  Names: [
    {
      id: "16359506819",
      Status: "0000000002",
      IsCurrent: true,
      Name: "JAKE",
      NameType: "Small",
      Postcode: "2000",
      Score: 100,
      State: "NSW",
    },
    {
      id: "16359506819",
      Status: "0000000002",
      IsCurrent: true,
      Name: "LONG",
      NameType: "Small",
      Postcode: "2000",
      Score: 100,
      State: "NSW",
    },
  ],
};

data.Names.forEach((obj) => {
  console.log(obj.Name);
});

Upvotes: 1

Related Questions