Search code examples
javascriptnode.jsjsonobjectloopbackjs

filter json objects by Id in Javascript


I have a JSON that returns an array of arrays of objects but what I want to do is to return an array of objects filtered by ID. This the code I built so far :

    let objComedien3=[];
      let i=0;

      for (var prop in bc) {
        objComedien3[i] = await app.models.cm_comediens_extraits_mp3.find({ where: { idMedia: bc[prop]} } );
        //here the result is giving me an array of arrays of objects so I had to do this :
        objComedien3[i]= Object.assign({}, objComedien3[i]);
        i++;
      }
      return objComedien3;

Final result I found is this :

[
  {
    "0": {
      "idSon": 33274,
      "idMedia": 42084,
      "qfDiffusion": null,
      "qfAccent": null,
      "qfAge": 169,
      "qfCartoon": null,
      "qfDoublage": null,
      "qfInterpretation1": 194,
      "qfInterpretation2": 194,
      "qfInterpretation3": 193,
      "qfImitation": null,
      "qfLangue": 145,
      "qfTimbre": 237,
      "qfType": 245,
      "qfGenre": "Masculin",
      "description": "Techno Music"
    }
  },
  {
    "0": {
      "idSon": 33275,
      "idMedia": 42086,
      "qfDiffusion": null,
      "qfAccent": null,
      "qfAge": 240,
      "qfCartoon": null,
      "qfDoublage": null,
      "qfInterpretation1": 196,
      "qfInterpretation2": 195,
      "qfInterpretation3": 247,
      "qfImitation": null,
      "qfLangue": 147,
      "qfTimbre": 236,
      "qfType": 176,
      "qfGenre": "Masculin",
      "description": "Techno Music"
    }
  }
]

Everything is fine except that I want to replace 0 by idSon and I didn't know how to manage that with Object.assign or any other function using javascript. Any help would be appreciated. Thank you so much


Solution

  • Try this:

     let objComedien3=[];
          let i=0;
    
          for (var prop in bc) {
            objComedien3[i] = await app.models.cm_comediens_extraits_mp3.find({ where: { idMedia: bc[prop]} } );
            //here the result is giving me an array of arrays of objects so I had to do this :
            let data= {}
            data[objComedien3[i][0]['idSon']] = objComedien3[i][0]
            objComedien3[i]= Object.assign({}, data);
            i++;
          }
          return objComedien3;