我有一个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的函数来管理它。 任何帮助,将不胜感激。非常感谢
答案 0 :(得分:3)
尝试一下:
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;
答案 1 :(得分:1)
我知道有一个已经被接受的答案,但是要以这种正确的方式进行操作,您应该得到总的结果,然后对其进行处理。
const dataset = await app.models.cm_comediens_extraits_mp3.find(
{ where: { idMedia: {inq: bc} } }//which gets all the media
).then((data)=>{//it is an array already
return data.reduce((p,c)=>{
p[c.idSon] = c;//or c.__data if you want the data. Or Object.assign
return p;
},{})
})
这样,您不必每次都查询。
答案 2 :(得分:0)
您可以通过使用object
而不是array
来执行此操作,这允许您输入idSon
键作为限定符,而不是array
中的索引:
let objComedien3 = {};
for (var prop in bc) {
let result = await app.models.cm_comediens_extraits_mp3.find({ where: { idMedia: bc[prop]} } );
let clonedResult = Object.assign({}, result[0]);
objComedien3[clonedResult.idSon] = clonedResult;
}
return objComedien3;
答案 3 :(得分:0)
for (let t of test) {
//replace your "0" with new "idSon"
t["idSon"] = t["0"];
//delete your "0" property object
delete t["0"];
}
//filter based on Id in this example I Used 33275
let filteredData: any = test.filter((o: any) => o["idSon"].idSon == 33275);