Andreas Engebretsen
Andreas Engebretsen

Reputation: 85

Struggling to update list in object array

Hi im having some issues when it comes to updating a specific object in my list based on the key inside the object. Instead of updating the object in the array with the correct key it adds a new object inside the list with the key as an array and then adds the key and the chosen value to that list. My expected result is that it goes into the correct object with the same key and adds the selected value to that list in my example output image that would be "Annet". {Kategori:["Annet"]}

//Find key that matches chosen key
            const addToFilter = valgtUnderFilter
                .map((filter: any) => Object.keys(filter))
                .flat()
                .find((filter: string) => filter === valgtHovedFilter)
            //map out all objects in list and try to update object with correct key
            valgtUnderFilter.map((f: any) => {
                //check if key exists in object (addToFilter = Kategori f = {Kategori : []})
                if (addToFilter in f) {
                    return setValgtUnderFilter([...valgtUnderFilter, { [addToFilter]: [...[addToFilter], valg] }])
                }
            })

[Output[1]

Upvotes: 0

Views: 96

Answers (2)

thanhdx
thanhdx

Reputation: 618

Because valgtUnderFilter is an array, not object, so [...valgtUnderFilter, { [addToFilter]: [...[addToFilter], valg] }] will just just return a clone array with adding new object at the end.

You can change the code so addToFilter is the object that have the key equal valgtHovedFilter, and then update the object directly.

Here is the code:

const addToFilter = valgtUnderFilter.find(obj => Object.keys(obj).includes(valgtHovedFilter));
if (addToFilter) addToFilter[valgtHovedFilter].push(valg);

Upvotes: 1

tstrand66
tstrand66

Reputation: 968

Based on your image i think the below gets you close if not perfectly at your goal.

const arr = [
  { Kategori: [] },
  { Status: [] },
  { RelevantBehandling: [] },
  { StudienForegarVed: [] },
  { AnsvarligHelseforetak: [] }
], 
  addToFilter = { Kategori: 'Annet' },
  addToFilterKey = Object.keys(addToFilter)[0],
  addToFilterVal = Object.values(addToFilter)[0];
let key, val;
arr.forEach(function (obj) {
  key = Object.keys(obj)[0];
  val = Object.values(obj)[0];
  key == addToFilterKey && val.push(addToFilterVal);
});
console.log(arr);

Upvotes: 0

Related Questions