radash
radash copied to clipboard
Feature request: Add a method to transform an object
Big fan of the project so far, the only thing preventing me from removing lodash is how I use it's transform
function to transform the shape of an array. Here's an example:
Say I get an object from a remote api that looks like this:
const data = {
id: 1,
source: {
image: 'https://example.com/test.jpg'
}
}
And I want to convert it to:
const data = {
id: 1,
imageUrl: 'https://example.com/test.jpg'
}
With lodash I can use transform
& get
like this:
const data = {
id: 1,
source: {
image: 'https://example.com/test.jpg'
}
}
const keys = {
id: "id",
"source.imageUrl": "imageUrl"
}
const transformKeys = transform(keys, (result, value, key) => get(data, key))
const result = transformKeys(data, keys)
// { id: 1, imageUrl: 'https://example.com/test.jpg' }
I'm wondering if there's already an easy way to achieve the same thing using radash, or if it could potentially be added?
Hey @jmcmullen thanks for creating an issue 👍
I've actually never even seen Lodash's transform
function before 👀 had to look it up. This is suuuuuper interesting to me because I need to solve for the same problem as well but I use a very different solution.
You're not the only one to ask for things of this dynamic/scripty nature and I'm happy to add one or two functions if they can help people make the change from Lodash. Currently, there is no get
function but there's an open issue #22 to make one. I'm planning to add it today or tomorrow and release it right away. Once it's in, you could use mapEntries
with get
for a similar solution.
import { mapEntries, get } from 'radash'
const keys = {
id: "id",
"source.imageUrl": "imageUrl"
}
const data = {
id: 1,
source: {
image: 'https://example.com/test.jpg'
}
}
const result = mapEntries(keys, (path, key) => [key, get(data, path)])