UgoL
UgoL

Reputation: 919

Access to object key values via javascript

This is my object structure encoded in json format:

[
{"playerid":"1","score":"10"},
{"playerid":"2","score":"40"},
{"playerid":"3","score":"20"},
{"playerid":"4","score":"9"},
{"playerid":"5","score":"20"}
]

How can I access to each values with javascript?

Maybe if I want to get all the key values like a simple array list format:

playerid = ["1","2","3","4","5"]

score = ["10","40","20","9","20"]

Since if I apply a console.log(data) it returns all the data correctly fetched. But if I try to use object notation for access to a specific value, for example by using console.log(data.playerid) or console.log(data["playerid"]) it returns undefined.

Any suggestions?

Upvotes: 0

Views: 93

Answers (4)

iamalismith
iamalismith

Reputation: 1571

The square brackets [] which surround your data indicate that the outermost structure is an array, not an object.

Inside the array are several objects, as indicated by the {} curly brackets.

In order to access the inner data, you must first pick an item from the array, using a numerical index.

To select the first object from the array:

data[0] // {playerid:"1",score:"10"}

To access properties within that object, you can use object notation:

data[0].playerid // "1"

You could also loop over the items in the array to access all the objects:

data.forEach((item)=>{
    console.log(item);
});

Upvotes: 0

Antonio Ganci
Antonio Ganci

Reputation: 515

Parse the data and access to the array element using index: JSON.parse(data)[0].playerid

to see all players:

var parsed = JSON.parse(data);

for(int i = 0; i < parsed.length; i++) {
   console.log(parsed[i].playerid);
   console.log(parsed[i].score);
}

Upvotes: 1

Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10093

Considering that data is the array that you have provided here, you cannot access console.log(data.playerid) because this array does not have any playerid property.

You need to iterate through this array, and then extract the required values in each iteration from the objects one by one.

var playersArray = [
{"playerid":"1","score":"10"},
{"playerid":"2","score":"40"},
{"playerid":"3","score":"20"},
{"playerid":"4","score":"9"},
{"playerid":"5","score":"20"}
];

var ids = [];
var scores = [];

playersArray.forEach(function( player ){
  var playerid = player.playerid;
  var score = player.score;
  
  ids.push( playerid );
  scores.push( score );
});//forEach();

console.log( ids );
console.log( scores );

Upvotes: 1

Grynets
Grynets

Reputation: 2525

It happens because you are using JSON encoded data.
Just simply decode it with JSON.parse(). And than access it as object.

Upvotes: 1

Related Questions