0

I add a json value from a response to a variable and then print it this way result: ${JSON.stringify(result)}, but what i want exactly is to get only one exact value from this json

here's the json

{
  "flags": [
    { "flagID": "0f0571b5-af7b-48e2-8418-044cbec0166d", "flagname": "lionsflag", "team": "lions", "membersnum": "4", "win": false },
    { "flags": "9819c0bd-e134-4950-a1ee-7f89450ee4b6", "flagname": "Barcaflag", "membersnum": "4", "win": true }
  ]
}

I only want to extract lionsflag string only from the first flagname, this value is able to change any time

  • like this: `flags.forEach((flag) => flag.flagname === "lionsflag" ? console.log(flag.flagname) : null);` – Joel Oct 25 '22 at 09:41

1 Answers1

1

You need to use Object.keys() to get all the keys and then check the related value is meet your demand or not

let data = {
  "flags": [
    { "flagID": "0f0571b5-af7b-48e2-8418-044cbec0166d", "flagname": "lionsflag", "team": "lions", "membersnum": "4", "win": false },
    { "flags": "9819c0bd-e134-4950-a1ee-7f89450ee4b6", "flagname": "Barcaflag", "membersnum": "4", "win": true }
  ]
}

let value = "lionsflag"
data.flags.filter(d => Object.keys(d).forEach(e =>{
  if(d[e] == value){
   console.log(e + ";" + value)
  }
}))

let prop ='flagname'
console.log(data.flags[0][prop])
flyingfox
  • 13,414
  • 3
  • 24
  • 39
  • That's not what i want exactly, I only want to extract `lionsflag` string, and this value is able to change any time – user7778555 Oct 25 '22 at 09:45
  • I think you didn't understood what i want exactly, the value is able to change so maybe in the next request the value will be XXXXX and not lionsflag, so i want to extract this sting – user7778555 Oct 25 '22 at 09:52
  • @user7778555 so my original answer is meet your demand,you just need to make the filter value(in your case is lionsflag) to a variable,and using the variable to filter value – flyingfox Oct 25 '22 at 10:01
  • this solution doesn't work I also tried console.log(data.flags[0].flagname) in the browser console it works but in the code it doesn’t – user7778555 Oct 25 '22 at 10:11
  • @user7778555 do you mean you just want to filter by `flagname` but the value might change? – flyingfox Oct 25 '22 at 10:14
  • yes, i only want to get the value of `flagname` and add it to a variable as a string – user7778555 Oct 25 '22 at 10:16
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/249036/discussion-between-lucumt-and-user7778555). – flyingfox Oct 25 '22 at 10:18