Well, how you display it is a different question. The question you are asking is about data manipulation. You need to transform one data object into another.
But it still isn’t clear to me. Will there always be only one id in the array? Or do you need to account for multiple?
You could do this with a for loop, but a reduce would work, too. You have to go through the elements and check if the new element for that is created - if not, create it; if it is, and your data. If you’re using a for loop, then create a new array and push onto it. If you’re using reduce, then you’re just reducing down to an array.
function helperFx(data){
let obj = {}
for(let [key, val] of Object.entries(data)){
const {name, id, color, quantity} = val
// check if obj has a key of selections if not
if( !('selections' in obj) ) obj['selections'] = []
// if id matches then lets add the name and another id and push them values
if(id === '1823817334'){
obj.name = name
obj.id = 'hdrezmDjPXcBVfYkusie'
obj['selections'].push({ color, quantity })
}
}
return obj
}
Hello, how would I display it in the screen? I tried with these but failed.
{value} will show this error :
Objects are not valid as a React child (found: object with keys {color, quantity}). If you meant to render a collection of children, use an array instead.
{value.id} or the {value.name} will show as undefined
{Object.entries(value).map(([key, value]) => {
return (
<p key={key}>
<li>
{key}
{value}
{console.log(value.id)} //this will show as undefined
</li>
</p>
);
})}