What is the best way to retrieve a specific property (such as key/value) from an array of objects using JavaScript?

Below is an array of objects:

data1 = [{id: 111, option: "ONE", actualPrice: 600, price: "450"}, {id: 112, option: "TWO", actualPrice: 700, price: "850"}, {id: 113, option: "THREE", actualPrice: 800, price: "450"}, {id: 111, option: "ONE", actualPrice: 600, price: "450"}]

I have updated the price property for ids 111 and 112. The updated array of objects now looks like:

data1 = [{id: 111, option: "ONE", actualPrice: 600, price: "650"}, {id: 112, option: "TWO", actualPrice: 700, price: "440"}, {id: 113, option: "THREE", actualPrice: 800, price: "450"}, {id: 111, option: "ONE", actualPrice: 600, price: "450"}]

Now, I need to extract only the particular properties in the form of an array of objects for keys whose values were changed. I want the extracted data in the following format and pass it to a function called handleUpdate:

I require the array of objects in the below format: const modifiedObj = [{actualPrice: 600, price: "650"}, {actualPrice: 700, price: "440"}]

handleUpdate(modifiedObj);

Answer №1

let list1 = [{id: 111, option: "ONE", actualPrice: 600, price: "450"}, {id: 112, option: "TWO", actualPrice: 700, price: "850"}, {id: 113, option: "THREE", actualPrice: 800, price: "450"}, {id: 111, option: "ONE", actualPrice: 600, price: "450"}]

let list2 = [{id: 111, option: "ONE", actualPrice: 600, price: "650"}, {id: 112, option: "TWO", actualPrice: 700, price: "440"}, {id: 113, option: "THREE", actualPrice: 800, price: "450"}, {id: 111, option: "ONE", actualPrice: 600, price: "450"}]

let updatedItems = [];
for(let index=0;index<list1.length;index++){
  if(list1[index].price!==list2[index].price){
    updatedItems.push({actualPrice: list1[index].actualPrice, price:list2[index].price});
  }
}

console.log(updatedItems);

Answer №2

Check out the link below for further insights. Consider using Array.prototype.some() if you need to determine whether any element satisfies a specified condition.

Exploring array objects

Alternatively, you may find the following code snippet helpful:

let results = []
data1.forEach((item, index) => {
    if (data1[index].price !== data2[index].price) {
        results.push({
            actualPrice: data[i].actualPrice,
            price: data2[i].price
        })
    }
})

console.log(results)

Answer №3

Give this a try! The following code snippet will generate a fresh array of objects named modifiedObj, containing only the actualPrice and Price.

const data = [{id: 111, option: "ONE", actualPrice: 600, price: "650"}, {id: 112, option: "TWO", actualPrice: 700, price: "440"}, {id: 113, option: "THREE", actualPrice: 800, price: "450"}, {id: 111, option: "ONE", actualPrice: 600, price: "450"}]

const modifiedObj = data.map(({actualPrice, price}) => ({actualPrice, price}))

The output will appear in this structure:

[{actualPrice: 600, price: "650"}, {actualPrice: 700, price: "440"}, {actualPrice: 800, price: "450"}, {actualPrice: 600, price: "450"}]

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

"Capturing" AJAX requests from Capybara / Selenium - Rails

Is it possible to monitor real AJAX requests in feature specs using Capybara/Selenium while my app is making AJAX calls on specific events like .click? I attempted to utilize the Teaspoon gem, but it seems to only allow access to fixture URLs (as mentione ...

What is the reason for the result of .splice being a singular object?

I've been working on updating my API and I've run into a problem. I need to replace the first element in an array like so: Given the data: const data = ["1", 2, 3, 4, 5, 6] I want the output to be: ["New_text", 2, 3, 4, 5] I attempted to use t ...

`Why my React function calls are not being tested properly with Jest and Sinon?`

I need help determining how many times my React class method is executed after an event. I've experimented with sinon.spy and jest.fn() but haven't had success. Attempt using sinon.spy: test('Example test', (done) => { const page ...

An addition operation in Javascript

Recently, I dipped my toes into the world of Javascript. However, I found myself puzzled by the script and its corresponding HTML output provided below. Script: <h1>JavaScript Variables</h1> <p id="demo"></p> <script> var ...

The pagination feature in DataTable does not retain the edited page after making changes

I have been encountering an issue while using DataTable serverside processing. My datatable includes an edit column, and when the edit link is clicked, a jQuery dialog box appears. After submitting the dialog box, an ajax.reload call is made. However, the ...

What is the best way to organize class usage within other classes to prevent circular dependencies?

The engine class presented below utilizes two renderer classes that extend a base renderer class: import {RendererOne} from "./renderer-one"; import {RendererTwo} from "./renderer-two"; export class Engine { coordinates: number; randomProperty: ...

Tips for styling a button upon being clicked

Is there a CSS technique to make a button change color when clicked with the mouse? I am aware of using ':hover' for changing color, but I need something specific to a left mouse click. I want the same functionality as a standard button but with ...

Learn the process of transmitting JSON data from a server-side (nodejs) to the client-side using Ajax

I have successfully set up a Node.js/express server to make a GET call to an API, which returns JSON data. Now, I am looking for ways to send this JSON data to my local JavaScript (client-server) in order to manipulate it by looping through and appending i ...

Tips for solving memory leaks in my vue.js / axios application?

I am facing an issue with a single page that displays rows from a table using inline vue.js script. The page fetches the list of rows on load and also fetches the table again when pusher events are received. Additionally, there is a modal window that allo ...

"Customizing the gaps between cluster bars on AmCharts JS for a clean and professional

Previously, I utilized the AmCharts flash version where creating clustered column/bar charts like the image below was a breeze. In that setup, the clustered bars were tightly packed with no spacing in between. However, transitioning to the JS version of Am ...

The Vue dragula plugin - drop event listener being triggered repeatedly

I am currently working on developing a web application that incorporates draggable elements utilizing the Vue.js framework and vue-dragula plugin. The main goal of the app is to allow users to drag elements across multiple containers. Within App.vue < ...

The JQuery loading symbol does not prevent keyboard interactions

I successfully implemented a Jquery busy indicator in my application using the following link: However, I noticed that even though it prevents users from clicking on input elements while loading, I can still navigate to these elements by pressing the tab ...

Issues with Knockout functionality due to retrieval of values from an external JSON file

Attempting to manipulate formulas in a spreadsheet-like fashion using knockout appears to be causing some issues with functionality. The data in question is sourced from an external Json file. Json file { "info": [ { "Name":"Newb ...

Use React to insert a leading zero next to a number in the input field if the number is greater than 10

I have scoured the web and consulted resources like this one but haven't found a solution that addresses my specific issue with adding padding to input numbers. My goal is to automatically add a leading zero whenever the number inside an input field i ...

My Angular project is experiencing issues with Socket.IO functionality

After successfully using a post method in my endpoint, I encountered an error when integrating it with socket io. The error pertained to a connection error and method not being found. Any help or source code provided would be greatly ap ...

Troubles with modifying website background using JavaScript

I'm looking to update my website background using JavaScript, starting with buttons before moving to a drop-down menu. I have the following code that successfully changes the background when the button is clicked: function selectText(test){ var a ...

Exploring directory organization in GraphQL Queries using GatsbyJS

In my portfolio, I have organized my work into categories, pieces, and pictures in a cascading order similar to a child-parent relationship. The folder structure reflects this hierarchy, with the main problem being explained in more detail below. Folder s ...

Update the value of ng-show to false after redirection to the home page from the login page using AngularJS

I am new to angularjs and encountered a problem which required me to change the value of ng-show="false" to ng-show="true" when the user is redirected to the home page after successfully logging in! This is what I am attempting to achieve: .controller(&a ...

The functionality of the Node.js/Express.js app is limited to operating solely on Port 3000

I'm currently troubleshooting an issue with my Node.js/Express.js app running on my server. It seems to only work on port 3000, and I'm trying to understand why. Here's what I've discovered: When I don't specify a port (app.liste ...

HTML element DIV positioned above the iframe

I am looking for a way to automatically place a "PLAY" div above each iframe instead of doing it manually. I have successfully done it manually but I'm not sure how to achieve the same result with a script or using CSS. Below is my HTML markup: < ...