Skip to content
Advertisement

JS – How do I make this object filled dynamically by an array?

I need help with the following: I am using material-table and its columns take an argument “lookup” which is an object with values. Its used for filtering and enabling multiselect inside the rows. The thing is, all examples I can find, are hardcoded, I am not able to find dynamically filled lookup objects. Now my question is; how can I fill the lookup object with values from an array:

 const [columns, setColumns] = useState([
 {
   title: 'Birth Place',
   field: 'birthCity',
   lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
 },
]);

I need an object like this:

{"PUE-200":"PUE-200", "PUE-201":"PUE-202" etc.}

The array I need to extract the data from is the following:

   0:{
    "ProjektNr": "PUE-200",
    "ProjektBeschreibung": "aa"
    }
   1:{
    "ProjektNr": "PUE-201",
    "ProjektBeschreibung": "aa"
    }

Will appriciate any help 🙂

Advertisement

Answer

Map the array of objects to an array of key-value pairs using the ProjektNr property and convert back to object using Object.fromEntries.

const data = [
  {
    "ProjektNr": "PUE-200",
    "ProjektBeschreibung": "aa"
  },
  {
    "ProjektNr": "PUE-201",
    "ProjektBeschreibung": "aa"
  }
];

const newMap = Object.fromEntries(data.map(el => [el.ProjektNr, el.ProjektNr]));

console.log(newMap);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement