Converting an Object into a new Object based on specific conditions

Looking at this object:

const data = {
    "title": "new book"
    "IsSale": 1,
    "price" : 100,
}

I would like to modify it to be:

const data = {
    "title": "new book"
    "IsSale": true,
    "price" : 100,
}

"IsSale": 1 > "IsSale": true

When dealing with arrays, we can use the reduce method for modification. However, when working with objects, is there a similar method available? Certainly, we wouldn't want to convert the object to an array, apply reduce, and then convert back to an object.

Answer №1

If the data is in an array, you can use the map method to make changes. But when dealing with an Object, are there any similar methods available?

If the data were actually an array, you would utilize the map function rather than reduce (assuming you meant reduce). Alternatively, you could use a standard loop.

To keep it simple, you can update an object by creating a new object literal:

const updated = {
    ...data,
    IsSale: !!data.IsSale
};

const data = {
    "title": "new book",
    "IsSale": 1,
    "price" : 100,
};

const updated = {
    ...data,
    IsSale: !!data.IsSale
};

console.log(updated);

If you need to do something more complex, you can achieve a similar result with objects using a series of intermediary steps involving arrays. This may include using Object.entries, map, and Object.fromEntries:

const updated = Object.fromEntries(
    Object.entries(data).map(([key, value]) =>
        [key, key === "IsSale" ? !!value : value]
    )
);

const data = {
    "title": "new book",
    "IsSale": 1,
    "price" : 100,
};

const updated = Object.fromEntries(
    Object.entries(data).map(([key, value]) =>
        [key, key === "IsSale" ? !!value : value]
    )
);

console.log(updated);

Alternatively, you can use a for-in loop as another approach:

const updated = {};
for (const key in data) {
    if (data.hasOwnProperty(key)) {
        const value = data[key];
        updated[key] = key === "IsSale" ? !!value : value;
    }
}

const data = {
    "title": "new book",
    "IsSale": 1,
    "price" : 100,
};

const updated = {};
for (const key in data) {
    if (data.hasOwnProperty(key)) {
        const value = data[key];
        updated[key] = key === "IsSale" ? !!value : value;
    }
}

console.log(updated);

(Please note that the example above uses the modern Object.hasOwn; consider applying a polyfill for outdated environments that lack support for it.)

Answer №2

It appears that you are interested in converting the value of a property within an Object to boolean (true/false). Check out this handy helper function designed for such conversions. This function is useful for adding and/or converting the property IsSale in an array of objects.

// You can use !!data.IsSale as a shortcut
const saleToBoolean = data => data.IsSale = Boolean(data.IsSale);

const data = [{
    "title": "new book",
    "IsSale": 1,
    "price" : 100,
  }, {
   "title": "another new book",
    "IsSale": 0,
    "price" : 110,
  }, {
    "title": "old book",
    "IsSale": 15,
    "price" : 50,
  }, {
    // Note: no IsSale property
    "title": "old book",
    "price" : 50,
  }];
  
data.forEach(saleToBoolean);
console.log(data);
.as-console-wrapper {
  max-height: 100% !important;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Numerous conditionals placed in the <head> section of the document

I need to run a script in all browsers except versions of IE below 9. The conditional statement for IE looks like this: <!--[if gt IE 8]> JavaScript code goes here <![endif]--> However, this code will only execute in IE9 and not in any ot ...

Run the script within the Angular scope

Hey there! I'm having an issue passing a JavaScript code through Angular scope, but when it renders on the view page, it's displayed as text. I even attempted using ng-Sanitize, but unfortunately, that didn't solve the problem. &lt;div ...

The error message is stating that there is a TypeError because it cannot read the property "bind" of an undefined value when using the ng

When trying to implement the ng-cropper directive, an angular binding for the cropper javascript image cropping library, I'm encountering the error message TypeError: Cannot read property 'bind' of undefined. It seems to be related to the fo ...

Create a custom validation function that accepts additional parameters

At the moment, I have implemented the following code but I haven't utilized the extra data yet. create-room.component.ts import { Component, Inject, OnInit } from '@angular/core'; import { AbstractControl, FormBuilder, FormControl, FormGroup ...

Retrieving the variable value instead of a reference using Ajax in ASP

After spending nearly two days trying to figure out this code and researching every possible solution, I still haven't been able to get it to work properly. It's likely that I'm implementing it incorrectly or missing something, so I've ...

Issue with deactivating attribute through class name element retrieval

There are multiple input tags in this scenario: <input type="checkbox" class="check" disabled id="identifier"> as well as: <input type="checkbox" class="check" disabled> The goal is to remov ...

Combining Update and Select Operations in Knex JS in a Single Query

With Knex JS - Can all elements from the row being updated be retrieved in a single query that combines both update and select operations? Currently, only the id of the updated row is returned by the update operation. let query = await knex('items&a ...

Accepting PUT requests on a JavaScript web server

I'm facing an issue retrieving PUT requests from a service within my Angular application. The problem lies in the fact that I cannot access the data from the request's body as it returns undefined. Below is the code snippet for reference. ANGULA ...

Retrieve the text label from the parent option group

Below is the HTML code snippet: <select id="categoryg"> <optgroup label="Main" value="binding"> <optgroup label="Sub" value="binding"> <option value="46&quo ...

Arrange all absolute divs equidistant from each other

I'm struggling with positioning multiple absolute divs inside a relative container using the CSS 'left' property. I want these inner divs to be evenly spaced regardless of how many there are, without setting fixed values for each. Currently ...

Synchronous AJAX calls can cause the browser to become unresponsive

I am facing an issue with my jQuery Ajax requests as they need to be synchronous, causing the browser to freeze until a response is received. The main problem I encounter is that I need to display a spinning icon while waiting for the response, but the fre ...

Develop objects with a fixed position - three.js

I am currently working on a game utilizing the three.js library and I have a specific requirement. I would like to incorporate a small "panel" on the screen that remains stationary regardless of the user's navigation through the 3D environment. Essent ...

What techniques can be employed to restrict or define imported data in React through mapping?

Starting my React journey with a single-page application, I am looking to bring in a static collection of personal information like this: { id: '1', link: 'john-doe', name: 'John Doe', title: 'Head of ...

The link in Next.js is updating the URL but the page is not refreshing

I am facing a peculiar issue where a dynamic link within a component functions correctly in most areas of the site, but fails to work inside a specific React Component - Algolia InstantSearch (which is very similar in functionality to this example componen ...

Exploring the concepts of function referencing and prototypical inheritance in relation to function scopes

Consider the scenario where there are two distinct directives: angular.module('demo').directive('functional', [function (){ var idempotentMethods = ['idempotentMethod', 'otherIdempotentMethod']; return { res ...

What are some ways I can integrate my Json object into my IONIC app rather than relying on a hardcoded object?

I stumbled upon this IONIC app's services.js file and found an example using a hardcoded object called "employees." Instead of using the hardcoded object, I wanted to use a JSON file. However, my attempt to make this change did not work as expected. I ...

How can you retrieve the chosen option's value in select2 and subsequently assign it to an input text using jquery?

I am a beginner in the world of jQuery and JavaScript, so please forgive me if this is a basic question. I am currently encountering an issue where I am unable to set the value obtained from a selected option in select2 to a text input field. Here's m ...

Which format to use for identifying a point within a polygon: JSON or KML

I am currently debating whether to use json or kml for storing polygons in a server file. The ultimate goal is to read this file and determine which polygon a specific point falls within. My initial inclination leans towards kml due to its efficiency in re ...

Having trouble displaying the input upon clicking the icon

Currently, I am honing my skills in vanilla JavaScript by working on a website project. In this project, I have implemented a feature where clicking on a fingerprint icon triggers an input field to appear for the user to enter their password. The code snip ...

What are the steps to rejuvenate a liferay portlet?

I am attempting to create a link that refreshes a Liferay portlet, but unfortunately it is not working as expected: <a href="javascript:Liferay.Portlet.refresh('#p_p_id_portletname')">link</a> Can someone help troubleshoot this i ...