Home > Software engineering >  How to obtain some value on json
How to obtain some value on json

Time:12-26

   var json = [
   {
      "bbox":[
         24.24112319946289,
         15.165281295776367,
         560.5425834655762,
         457.0700454711914
      ],
      "class":"person",
      "score":0.8514186143875122
   },
   {
      "bbox":[
         291.99377059936523,
         84.65291976928711,
         315.9793281555176,
         376.3008499145508
      ],
      "class":"tv",
      "score":0.8043261766433716
   },
   {
      "bbox":[
         296.79737091064453,
         353.7140464782715,
         252.2602081298828,
         114.29803848266602
      ],
      "class":"person",
      "score":0.5516218543052673
   }
]

Hi, I need help, I need to obtain data all 'class : person' from json above. How to do that?

CodePudding user response:

Please try this

const ids = ["person"];
const data = [
   {
      "bbox":[
         24.24112319946289,
         15.165281295776367,
         560.5425834655762,
         457.0700454711914
      ],
      "class":"person",
      "score":0.8514186143875122
   },
   {
      "bbox":[
         291.99377059936523,
         84.65291976928711,
         315.9793281555176,
         376.3008499145508
      ],
      "class":"tv",
      "score":0.8043261766433716
   },
   {
      "bbox":[
         296.79737091064453,
         353.7140464782715,
         252.2602081298828,
         114.29803848266602
      ],
      "class":"person",
      "score":0.5516218543052673
   }
];

const data2 = data.filter( i => ids.includes( i.class ) );

console.info( data2 );

CodePudding user response:

[Updated]:

You can filter the array to get the desired object:

const person = json.filter((item) => item.class === 'person')

This will return the object having class key's value as person

[ 
   {
      "bbox":[
         24.24112319946289,
         15.165281295776367,
         560.5425834655762,
         457.0700454711914
      ],
      "class":"person",
      "score":0.8514186143875122
   },{
      "bbox":[
         296.79737091064453,
         353.7140464782715,
         252.2602081298828,
         114.29803848266602
      ],
      "class":"person",
      "score":0.5516218543052673
   }
]
  • Related