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' }))
})

Cristian Muscalu
  • 9,007
  • 12
  • 44
  • 76
  • If it's okay to mutate `obj`, then: `obj?.item2?.dynamicItem1.push({type: 'added'});`. And, similarly: `obj?.item2?.dynamicItem2.push({type: 'added'});`. Please try & share feedback. – jsN00b Apr 01 '22 at 12:37
  • I don't know the name of `dynamicItem1 ` key. It's why i called it dynamic. – Cristian Muscalu Apr 01 '22 at 12:38
  • Okay, so, we need to add `{type: 'added'}` to every `array` value within `item2` object - is that correct? – jsN00b Apr 01 '22 at 12:39
  • Why did you choose `.map()` when `.forEach()` would be the more obvious tool (unless you need an actual copy of `obj`)? Why `Object.keys()` when you need the values of the `obj` (-> Òbject.values()` or `Object.entries()`)? – Andreas Apr 01 '22 at 12:39
  • 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], ... – Andreas Apr 01 '22 at 12:41
  • 1
    @jsN00b correct – Cristian Muscalu Apr 01 '22 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. :-) – jsN00b Apr 01 '22 at 12:43
  • 1
    @CristianMuscalu - what about this? https://jsfiddle.net/libik/hujx7fz6/4/ (cannot post it here as they closed it :/ ) – libik Apr 01 '22 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. – Andreas Apr 01 '22 at 13:21
  • @libik big thanks for going out of you way to help a brother out! I will use your solution <3 – Cristian Muscalu Apr 01 '22 at 14:43
  • @CristianMuscalu - sure thing! btw: the copying of object is not necessary if you are fine that original object will change. Also the library used there is `lodash` (the `_` sign) – libik Apr 05 '22 at 07:48

0 Answers0