0

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]

1
  • 2
    Please provide sample input and corresponding expected output in JavaScript syntax (text) in your question, not as an image. Commented Feb 6, 2020 at 14:48

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this worked. Reading your example made perfect sense.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.