Transforming Object Properties with JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the transform function in JavaScript which allows us to apply a specified function against an accumulator and each key in an object. By using Object.keys() and Array.prototype.reduce(), we can easily iterate over each key in an object and perform the desired transformation. This lab will provide hands-on experience with this useful function and demonstrate its practical applications in JavaScript programming.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28667{{"`Transforming Object Properties with JavaScript`"}} javascript/data_types -.-> lab-28667{{"`Transforming Object Properties with JavaScript`"}} javascript/arith_ops -.-> lab-28667{{"`Transforming Object Properties with JavaScript`"}} javascript/comp_ops -.-> lab-28667{{"`Transforming Object Properties with JavaScript`"}} javascript/array_methods -.-> lab-28667{{"`Transforming Object Properties with JavaScript`"}} javascript/higher_funcs -.-> lab-28667{{"`Transforming Object Properties with JavaScript`"}} javascript/destr_assign -.-> lab-28667{{"`Transforming Object Properties with JavaScript`"}} end

Object Transformation

To start practicing coding, open the Terminal/SSH and type node.

The transform function applies a specified function against an accumulator and each key in the object, from left to right. Here's how to use it:

  • Use Object.keys() to iterate over each key in the object.
  • Use Array.prototype.reduce() to apply the specified function against the given accumulator.
const transform = (obj, fn, acc) =>
  Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);

Here's an example:

transform(
  { a: 1, b: 2, c: 1 },
  (r, v, k) => {
    (r[v] || (r[v] = [])).push(k);
    return r;
  },
  {}
); // { '1': ['a', 'c'], '2': ['b'] }

Summary

Congratulations! You have completed the Transform Object lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like