简体   繁体   中英

Dynamically pass keys to map to new object

Sorry for the confusing title, wasn't sure how to describe this in a one liner.

I have the following utility function:

module.exports.reduceObject = item => (({ price, suggested_price }) => ({ price, suggested_price }))(item);

Which takes the values from the keys price and suggest_price and returns a new object with just those keys and values.

I can then turn an object like this:

inspect_link: 'steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198279893060A%item_id%D9567622191659726240',
price: '2.15',
suggested_price: '2.90',
is_featured: false,
float_value: '-1.00000',
pattern_info: 
 { paintindex: 0,
   paintseed: null,
   rarity: 3,
   quality: 4,
   paintwear: null },
is_mine: false,
tags: { type: 'Collectible', quality: 'Normal', rarity: 'High Grade' },
fraud_warnings: [],
stickers: null,
updated_at: 1501880427 }

Into it's reduced version:

{"price":"2.59","suggested_price":"1.41"}

Which I'm then storing in a MongoDB database.

I'd like to be able to pass in the keys (such as price , suggested_price dynamically so I can reduce any object to a smaller version of itself, but I'm struggling to find a good implementation.

I wrote something such as:

module.exports.reduceObject = (item, keys) => (({ ...keys }) => ({ ...keys }))(item);

which isn't valid, but I honestly have no idea how to even approach this.

Can anybody offer a solution?

There is already a powerful lodash library which does what you need. It has pick function which returns an object composed of the picked object properties:

let newItem = _.pick(item, ['price', 'suggested_price']);

I find lodash's implementation hard to read. If you're like me, here's a simpler implementation:

function pick(object, keys) {
    const result = {};
    for (const key of keys) {
        if (object.hasOwnProperty(key)) {
            result[key] = object[key];
        }
    }
    return result;
}

Depending on your use, it can be important to check whether the key is actually in the source object. This has slipped me up before.

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