I have a data inside of my array, which looks like this.
const arr = [ { devSth: { h1: [1], h2: [1], } }, ];
I have a function, which should modify this array. It looks like this:
const modifyArr = (data) => { data.forEach(el => { let keys = el.devSth && Object.keys(el.devSth); keys.forEach(key => { el.devSth[key].map(el => { return { name: el, val: 'lalala' } }) }) }) return data; }
Then I am using my function:
const newArr = modifyArr(arr); console.log(newArr);
Expected output:
[{ devSth: { h1: [{name: 1, val: 'lalala'}], h2: [{name: 1, val: 'lalala'}] } }]
Actual output:
[{ devSth: { h1: [1], h2: [1] } }]
Would appreciate any help.
CodePudding user response:
you are mapping the values, but not setting them (line 5) :
const modifyArr = (data) => {
data.forEach(el => {
let keys = el.devSth && Object.keys(el.devSth);
keys.forEach(key => {
el.devSth[key] = el.devSth[key].map(el => {
return {
name: el,
val: 'lalala'
}
})
})
})
return data;
}
this is untested.
CodePudding user response:
You dont assign the result of the .map operation back to the original keys h1 and h2. Just change
el.devSth[key].map(el => {
console.log("a")
return {
name: el,
val: 'lalala'
}
})
to
el.devSth[key] = el.devSth[key].map(el => {
console.log("a")
return {
name: el,
val: 'lalala'
}
const arr = [{
devSth: {
h1: [1],
h2: [1],
}
}, ];
const modifyArr = (data) => {
data.forEach(el => {
let keys = el.devSth && Object.keys(el.devSth);
keys.forEach(key => {
el.devSth[key] = el.devSth[key].map(el => {
console.log("a")
return {
name: el,
val: 'lalala'
}
})
})
})
return data;
}
const newArr = modifyArr(arr);
console.log(newArr);
