首页 > 解决方案 > 在Javascript中按Id过滤json对象

问题描述

我有一个 JSON,它返回一个对象数组的数组,但我想做的是返回一个按 ID 过滤的对象数组。这是我到目前为止构建的代码:

    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;

我发现的最终结果是这样的:

[
  {
    "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"
    }
  }
]

一切都很好,除了我想用 idSon 替换 0 并且我不知道如何使用 Object.assign 或任何其他使用 javascript 的函数来管理它。任何帮助,将不胜感激。太感谢了

标签: javascriptnode.jsjsonobjectloopbackjs

解决方案


尝试这个:

 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;

推荐阅读