Conditionally add a new property to JS objects

Introduction

Recently, I published an article about How to spread objects in Javascript conditionally.

This article won’t have much difference from the previous one, it rather demonstrates how to apply the operation on the opposite side, So we’ll learn how we can add/inject a property into a javascript object conditionally.


Conditionally add a property to objects in JS

Consider we have two simple JS objects, both represents a person’s details, one is an employee, and the other is an investor, and we wanted to manipulate/add properties to each object during the time.

let employee = {
    name: 'John Doe',
    age: 21,
    iEmployee: true,
    isInvestor: false
};

let investor = {
    name: 'Andy Smith',
    age: 22,
    iEmployee: false,
    isInvestor: true
};

As shown above, the employee object has two properties (iEmployee, isInvestor ) which indicates that he’s an only employee and not an investor.

The vice-versa in the investor object, we’ve two properties (iEmployee, isInvestor ), which indicates that he’s an only investor, not an employee.

Now, let’s assume we’re going to pass over the persona’s objects, and manipulate them based on the object properties that they hold. For this purpose, we will add the following function, which does a check on each object’s properties, and based on them (iEmployee, isInvestor ), It adds new properties to each object.

function manipulatePersona(obj) {
    return {
        ...obj,
        ...(obj.iEmployee && {hasSalary: true}),
        ...(obj.isInvestor && {hasEquity: true})
    }
}

The logic in the above function does the following:

  • It does return a new object return {}
  • Spread the original object values ...obj
  • Check if the object has iEmployee property, if yes, it adds a new object of a single property {hasSalary: true}, and spread ... that into the returned object.
  • Same as in the previous point, It does check if the object has isInvestor property, if yes, it adds a new object of a single property {hasEquity: true}, and spread ... that into the returned object.

Now, let’s try putting it all together and see the output:

let employee = {
    name: 'John Doe',
    age: 21,
    iEmployee: true,
    isInvestor: false
};

let investor = {
    name: 'Andy Smith',
    age: 22,
    iEmployee: false,
    isInvestor: true
};

function manipulatePersona(obj) {
    return {
        ...obj,
        ...(obj.iEmployee && {hasSalary: true}),
        ...(obj.isInvestor && {hasEquity: true})
    }
}

console.log(manipulatePersona(employee));
// Output:
// { name: 'John Doe', age: 21, iEmployee: true, isInvestor: false, hasSalary: true }

console.log(manipulatePersona(investor));
// Output:
// { name: 'Andy Smith', age: 22, iEmployee: false, isInvestor: true, hasEquity: true }

That’s Awesome!

Trying with a third person, that he’s an employee and an investor, it would result in the following:

let employeeAndInvestor = {
    name: 'Andy Smith',
    age: 22,
    iEmployee: true,
    isInvestor: true
};

console.log(manipulatePersona(employeeAndInvestor));
// Output:
// { name: 'Andy Smith', age: 22, iEmployee: true, isInvestor: true, hasSalary: true, hasEquity: true }

That’s it for How to Conditionally add a new property to JS objects.

Photo from Unsplash


Related posts

Related Posts

How to Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

Leave a Reply

%d bloggers like this: