You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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:

  1. Added error handling: I added a check for err in the callback to reject the promise properly—this prevents unhandled promise rejections which can cause issues in your app.
  2. Final array conversion: Instead of assigning the ID-keyed object directly to result.mp3, we use Object.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" }
    ]
    
  3. Retains ID-based processing: By keeping the object with idSon as keys, you still get the benefit of deduplication (if your SQL query returns duplicate idSon entries, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:29:21