简体   繁体   中英

Object push Firebase, how to remove key names from pushed items

I have this Object.key code that pushes all items:

const cloned_items = [];

Object.keys(items).sort().map(key => {
    let item = {
        [`item-${uid}`]: {
            item: false
        }
    }

    cloned_items.push({ ...item });
});

database.ref('/app/items').update({
    ...cloned_items
})

but this produces following result:

"0" : {
    "timeslot-87dah2j" : {
        item: false
    }
},
"1" : {
    "timeslot-7s1ahju" : {
        item: false
    }
}

instead of:

"timeslot-87dah2j" : {
    item: false
},
"timeslot-7s1ahju" : {
    item: false
}

any idea ?

It seems like you want to create a plain object, not an array.

In that case:

const cloned_items = Object.assign(...Object.keys(items).map(uid =>
    ({ [`item-${uid}`]: {item: false} })
));

NB: sorting is of no use when creating an object -- its keys are supposed to have no specific order.

You're creating an array of objects. Seems like you want to use .reduce() to create a single object from the array.

const cloned_items = Object.keys(items).sort().reduce((obj, key) =>
    Object.assign(obj, { [`item-${uid}`]: { item: false } })
, {});

Your code doesn't show where uid is coming from, but I assume you meant key there, along with timeslot instead of item .


You may find Object.defineProperty to be cleaner, though you'll need to set up the property descriptor as you want it.

const cloned_items = Object.keys(items).sort().reduce((obj, key) => 
    Object.defineProperty(obj, `item-${uid}`, {value:{item: false}})
, {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM