I'm trying to change the value of an object that is in an array that is nested in an object. I don't even know if I explained how nested it is well enough...
here is what it looks like
{
household and furniture: [{…}, {…}],
school stuffs: [{…}, {…}]
}
so, I tried to map through it and got my code to look like this now..
{
0: {school stuffs: [{…}, {…}]},
1: {household and furniture:[{…}, {…}]}
}
how do I get the data to look the exact way it was initially (without the 0 and 1 as keys) after I edit the field
here is the code I used to edit the field
const checkAll = e => {
const newArray = Object.keys(productArray).map(elem => {
return {[elem]: productArray[elem].map(innerElem => {
return { ...innerElem, completed: e.target.checked }
}) }
})
console.log({...newArray})
setProductArray(newArray)
}
You are using map which essentially returns an Array and you're expecting an Object. When you spread using {...newArray}, it spreads the array using the indices as keys for the resulting object, hence, the 0 and 1.
You can ideally use a reduce to return an object, and use it directly.
const checkAll = e => {
const obj = Object.keys(productArray).reduce((acc, curr) => {
acc[curr] = [...productArray[curr].map(item => ({...item, completed: e.target.checked}));
return acc;
}, {});
console.log(obj);
setProductArray(obj)
}
You can do it in single line:
const obj ={household and furniture: [{…}, {…}],school stuffs:[{…},{…}]
}
let flatObj = Object.values(obj).reduce((acc, curr) => ({ ...acc, ...curr }), {});
Can you make thing like that
const example = { hello : {name : "kareem"} , example : [1,2] }
const converter = (inp)=>{
return Object.assign({},Object.keys(inp).map(key=> {return {[key] : inp[key]}}))
}
console.log(converter(example))