Reputation: 1211
Is there any way how to pick property from object into new object under different key?
E.g.:
// pseudo
let a = {prop1: 'a', prop2: 'b', prop3: 'c'}
_.pickAs(a, {prop1: 'first', prop3: 'second'}
// {first: 'a', second: 'c'}
Upvotes: 1
Views: 1690
Reputation: 191976
You can use Array.reduce()
with Object.entries()
to create a pickAs()
method:
const a = {prop1: 'a', prop2: 'b', prop3: 'c'}
const pickAs = (obj, props) =>
Object.entries(obj)
.reduce((r, [k, v]) => {
if(k in props) r[props[k]] = v;
return r;
}, {});
const result = pickAs(a, {prop1: 'first', prop3: 'second'});
console.log(result) // {first: 'a', second: 'c'}
Upvotes: 4
Reputation: 32166
You can use lodash _.mapKeys
method to rename the keys after you've picked them from the object. As far as I know there's no method to do both at the same time, but this works quite well:
const a = {prop1: 'a', prop2: 'b', prop3: 'c'}
const result = _.mapKeys(_.pick(a, ["prop1", "prop3"]), (v, k) => k.endsWith("1") ? "first" : "second");
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
You'll want to replace the mapKeys
second argument with a function that fits your actual use case. That function is invoked with two arguments: the value and the key, and should return the new key that you want.
Upvotes: 0