how to access nested object inside map code example
Example 1: js map nested objects
const items = [
{ id: 1, name: 'Nike Air Max 97', inStock: true },
{ id: 2, name: 'Adidas Continental', inStock: true },
{ id: 3, name: 'Adidas Supercourt', inStock: true },
{ id: 4, name: 'Nike Jordan Dunks', inStock: true }
]
const itemsCopy = items.map(item => {
if (item.id === 4) {
return { ...item, inStock: false }
}
return { ...item }
})
console.log('og', items)
console.log('new', itemsCopy)
Example 2: javascript map value nested object
function deepMap(obj, mapfn) {
function recurse(obj) {
let res = {}
console.log(JSON.stringify(obj))
for (const key in obj) {
const value = obj[key];
if (value && typeof value === 'object') {
res[key] = recurse(value);
} else {
res[key] = mapfn(value);
}
}
return res
}
return recurse(obj);
}
deepMap({'a':1, 'b':{'c':3}}, (val) => val+1)