Skip to content
Advertisement

How to create a new object as a subset of object properties of any depth, while renaming properties on the fly

Although a plethora of posts have been dedicated to the topic, I still couldn’t find a satisfying idea how to subset object properties of any depth. More so, I would also like to rename the selected keys on the fly.

What I’m aiming to achieve is a generic function, let’s call it select(), that accepts two inputs:

  • an object of data
  • an object in which keys represent the desired new name, and values specify the path to desired properties.

For example, consider the following data:

JavaScript

My goal is to call select() this way:

JavaScript

where the resulted earthDataSubset is

JavaScript

At this point, one may ask why I don’t simply do this:

JavaScript

This won’t work because typically, my data arrives as an array of objects, so I need to map over the array and apply the same select procedure such as in:

JavaScript

Admittedly, I could have called .map() array method simply as:

JavaScript

And get the desired output:

JavaScript

Nevertheless, I’m looking to create my own generic select() function that accepts one object, and subsets it. The benefit of such approach is its flexibility. I can use it standalone on a single object, plus allowing me to scale select() to an array of objects when needed, by doing something like:

JavaScript

From looking around in StackOverflow posts, I found this one to be the closest. But neither do I understand how to shape it to my needs, nor whether its recursive mechanism actually required in my situation. By contrast, this post offers a ton of solutions for the simple scenario of subsetting, but none is addressing the issue of nested properties.

Advertisement

Answer

You can do something like this

JavaScript

Explanation inner reduce part

path.reduce((current, segment) => current[segment] ?? undefined , data)

path is an array of property nested inside data

path.reduce cycle all these property name

example

path = ['continents', 'asia', 'population']

in the first iteration

  • current is data your object (I omit it because it’s a bit long)
  • segment is ‘continents’
  • return data[‘continents’]

second iteration

  • current is data[‘continents’]
  • segment is ‘asia’
  • return data[‘continents’][‘asia’]

You got the idea

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement