1

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;
 });

4 Answers4

2

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
smuckert
  • 138
  • 12
2

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}`)
}
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
2
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);
});
Ariful hasan
  • 313
  • 3
  • 9
0

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);
libik
  • 22,239
  • 9
  • 44
  • 87