0

Desired result: Insert an object into each dynamicItem and have the full obj object.

const obj = {
  item1: {},
  item2: {
    dynamicItem1: [{ id: 'one' }, ], // add another prop here {type: 'added'}
    dynamicItem2: [{ id: 'one' }, ] // add another prop here {type: 'added'}
  },
}

My attempts: I managed to insert the object, but i can't think how to rebuild the full object and it also feels like i'm doing it wrong already.

const result = Object.keys(obj.item2).map(key => {
    return obj.item2[key].map(item => ({ ...item, type: 'added' }))
})

11
  • 2
    Split up the steps and you will find answers to all of them here on SO: iterate over all (unknown) properties of an object, add property to existing object[, clone an object], ... Commented Apr 1, 2022 at 12:41
  • 1
    @jsN00b correct Commented Apr 1, 2022 at 12:41
  • 1
    Please try this and share your feedback: const res = {...obj, item2: Object.fromEntries(Object.entries(obj.item2).map(([k,v]) => ([k, [...v].concat([{type: 'added'}])])))};. Specifically what errors or issues are faced. And, as @Andreas has noted, SO has all of these ideas in various questions. :-) Commented Apr 1, 2022 at 12:43
  • 1
    @CristianMuscalu - what about this? jsfiddle.net/libik/hujx7fz6/4 (cannot post it here as they closed it :/ ) Commented Apr 1, 2022 at 12:56
  • 1
    "...they closed it" - because all necessary steps have already been answered: how to iterate over properties of an object, how to add a new property to an object. So no need for yet another custom answer. Commented Apr 1, 2022 at 13:21

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.