Помогите сделать новый объект js

вот исходные данные:

let arr =  [
   {
    "model": "model",
    "ports": [
      {
        "id": "default",
        "methods": [
          {
            "command": "all_off",
            "smth": "activate",         
          },
        ],
        "name": "Default, All Off",
      },
    ],
  },
  {
    "model": "model2",
    "ports": [
      {
        "id": "smart",
        "methods": [
          {
            "command": "smart_on",
            "smth": "power_on",          
          },
          {
            "command": "smart_left",
            "smth": "balance_left",         
          }
        ],
        "name": "Smart Soundbar",
      },
    ],
  },
]

нужно получить объект формата:

obj = {
    "id" : ["command"],
    "id" : ["command", "command"]
}
    
   
let obj = {
    "default" : ["all_off"]
    "smart" : ["smart_on", "smart_left"]
}

не могу никак понять...


Ответы (1 шт):

Автор решения: entithat

Используем функцию reduce, потому она проходится по массиву и возвращает какое-то одно вычисленное значение, в нашем случае - объект.

const arr = [{
    "model": "model",
    "ports": [{
      "id": "default",
      "methods": [{
        "command": "all_off",
        "smth": "activate",
      }, ],
      "name": "Default, All Off",
    }, ],
  },
  {
    "model": "model2",
    "ports": [{
      "id": "smart",
      "methods": [{
          "command": "smart_on",
          "smth": "power_on",
        },
        {
          "command": "smart_left",
          "smth": "balance_left",
        }
      ],
      "name": "Smart Soundbar",
    }, ],
  },
];

console.log(
  arr.reduce((acc, e) => {
    acc[e.ports[0].id] = e.ports[0].methods.map(m => m.command);
    return acc;
  }, {})
);

P.S. Но не ясно как должен выглядеть объект, если в ports будет не одно, а много значений.

→ Ссылка