如何用JavaScript移除对象ID过滤并转为简易格式
Solution
Got it, here's how you can adjust your code to get the array structure you want while still leveraging the ID key to handle duplicates (which your current code does implicitly by overwriting entries with the same idSon):
Modified Code
let resultMp3 = {}; let sqlPromise = await new Promise(function (resolve, reject) { var ds = app.datasources.mydb; var sql = `....`; ds.connector.execute(sql, [], function (err, cm_comediens_extraits_mp3s) { if (err) { // Don't forget to handle errors properly! return reject(err); } if (cm_comediens_extraits_mp3s.length === 0){ resultMp3 = {}; } else { for(var i=0; i<cm_comediens_extraits_mp3s.length;i++){ let extraitMp3 = cm_comediens_extraits_mp3s[i]; let mp3 = {}; mp3["idSon"] = extraitMp3.idSon; mp3["description"] = extraitMp3.description; mp3["Typenom"] = valueList[extraitMp3.type].fr; // Keep using ID as key to avoid duplicate entries resultMp3[extraitMp3.idSon] = mp3; } } resolve(resultMp3); }); }); // Convert the ID-keyed object to a flat array of mp3 objects result.mp3 = Object.values(resultMp3);
Key Changes & Explanations:
- Added error handling: I added a check for
errin the callback to reject the promise properly—this prevents unhandled promise rejections which can cause issues in your app. - Final array conversion: Instead of assigning the ID-keyed object directly to
result.mp3, we useObject.values(resultMp3). This method extracts all the mp3 objects from the original object and wraps them in an array, giving you exactly the structure you requested:"mp3": [ { "idSon": 33274, "description": "Techno Music", "Typenom": "Billboard" }, { "idSon": 33275, "description": "Techno Music", "Typenom": "Pub Cd/Dvd" } ] - Retains ID-based processing: By keeping the object with
idSonas keys, you still get the benefit of deduplication (if your SQL query returns duplicateidSonentries, only the most recent one is kept)—just like your original code did.
If you’re certain your SQL query will never return duplicate idSon entries, you could simplify further by initializing resultMp3 as an array and pushing each mp3 object into it directly. But since you mentioned needing to use the ID for processing, the above approach keeps that advantage while delivering the array structure you want.
内容的提问来源于stack exchange,提问作者Ahmed
相关产品推荐
相关产品推荐

