kanishka kumarasiri
kanishka kumarasiri

Reputation: 153

node js access value in json result and get the value

i have following json object which i get from API end point

  let myjson = { Team1: { SCORE: 10 } }

i want to access the score inside Team but not able to complete as i need to just the result as 10

i have tried following code but not able to get the result

 for(var attribute name in JSON.parse(myjson)){
        return  console.log(attributename+": "+body[attributename]);
    }

i also used bellow code

const userStr = JSON.stringify(myjson);

 JSON.parse(userStr, (key, value) => {
 if (typeof value === 'string') {
 return value.toUpperCase();
 }
return value;
 });

Upvotes: 1

Views: 385

Answers (4)

Ariful hasan
Ariful hasan

Reputation: 323

you also can use this if it fulfills your query.
here is the code.

let myjson = {Team1: {SCORE:10}, Team2: {SCORE: 20}};
Object.keys(myjson).forEach(function(item) {
  console.log(myjson[item].SCORE);
});

Upvotes: 2

Marcos Casagrande
Marcos Casagrande

Reputation: 40374

myjson is already an Object, you don't need to do JSON.parse nor JSON.stringify on it.

Just access the property directly:

console.log(myjson.Team1.SCORE)

If you have multiple teams, or want to access it dynamically:

const obj = { Team1: { SCORE: 10 }, Team2: { SCORE: 20 } }

for(const [team, value] of Object.entries(obj)) {
   console.log(`${team}: ${value.SCORE}`)
}

Upvotes: 2

libik
libik

Reputation: 23029

Not sure if there can be more teams in that object, so I put here some more complex solution and then the straightforward one.

const myjson = { Team1: { SCORE: 10 }, Team2: { SCORE: 20 } }
const result = Object.keys(myjson).map(key => myjson[key].SCORE);

console.log('For dynamic resolution', result);
console.log('If there is only Team1', myjson.Team1.SCORE);

Upvotes: 0

smuckert
smuckert

Reputation: 170

Not a node developer but why do you need to json.stringify it? Can't you just reach the value with dot notation like this:

myJson.Team1.SCORE

Upvotes: 2

Related Questions