简体   繁体   中英

Extract properties from and object and union objects in JavaScript [on hold]

I need to implement two functions:

1) A function that constructs a new object with the properties extracted from another object by given names (probably an array of names).

2) A function that constructs a new object that has all properties of a multiple (one or many) given objects.

What is the optimal way to implement them? Can lodash lib help?

EDIT1:

Probably an obvious solution is to iterate over Object.keys(obj)

Thanks JonasWilms and Barmar: The solutions are:

1) _.pick

2) Object.assign

Sample code:

getOrderKey(order)
{
    return {
        id: order.id,
        marketId: this.marketId,
        userId: this.app.userId,
    };
}

async insertOrder(order)
{
    await this.db.insertObject('tb_order', 
        Object.assign(
            this.getOrderKey(order),
            _.pick(order, 'type', 'side', 'status', 'price', 'amount', 'cost', 'filled', 'remaining'), 
        ));
}

where this.db.insertObject is a function that generates SQL insert statement by a given table and an object.

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