[英]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. 它从键
price
和suggest_price
获取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. 然后将其存储在MongoDB数据库中。
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. 我希望能够在按键(如通过
price
, suggested_price
动态所以我可以在任何物体减少自身的缩小版,但我在努力寻找一个良好的实施。
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. 已经有功能强大的lodash库可以满足您的需求。 It has
pick
function which returns an object composed of the picked object properties: 它具有
pick
函数,该函数返回一个由picked对象属性组成的对象:
let newItem = _.pick(item, ['price', 'suggested_price']);
I find lodash's implementation hard to read. 我发现lodash的实现很难阅读。 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.
这以前使我不知所措。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.