Comparing object keys in JavaScript for property values

I'm currently working on comparing the properties of objects by their keys. Here is some example data:

const data = [{
    "name": "John",
    "value": "30"
}, {
    "name": "Cindy",
    "value": "50"
}, {
    "name": "Mathew",
    "value": "80"
}, {
    "name": "Mike",
    "value": "35"
}];

The goal is to compare the values (value) of the names John and Mike. If Mike's value differs from John's, I want to update Mike's value with John's value. Below is a proposed algorithm:

data.map(obj => {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      let johnValue;
      let mikeValue;

      if(obj[key] == 'John') {
        johnValue = Number(obj.value)
      }
      else if(obj[key] == 'Mike') {
        mikeValue = Number(obj.value)
      }

      if(johnValue != mikeValue) {
        newData = {
          ...data,
          "Mike":  johnValue
        } 
      }
    }
  }
})

Once executed, I expect the data to be updated as shown below:

const data = [{
        "name": "John",
        "value": "30"
    }, {
        "name": "Cindy",
        "value": "50"
    }, {
        "name": "Mathew",
        "value": "80"
    }, {
        "name": "Mike",
        "value": "30"
    }];

Is there a more efficient way to accomplish this using ES6 features? Fiddle

Answer №1

A shorter approach is possible

const findMikeIndex = data.findIndex(v => v.name === 'Mike')
const findJohnRecord = data.find(v => v.name === 'John')

if (data[findMikeIndex].value !== findJohnRecord.value) {
  newData = [...data]
  newData[findMikeIndex] = { name: 'Mike', value: findJohnRecord.value }
} 

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

React typescript is handling various promise response types, causing strange behavior in type-checking

I recently started utilizing the and I seem to be encountering a perplexing issue. If further context is needed, please let me know and I will provide it. All the necessary functions and types are mentioned below my explanatory paragraphs. Your assistance ...

Bundling extraneous server code in client rollup

Can someone help me understand why the following code is being included at the top of my browser bundle by Rollup? It seems like these references are not used anywhere from my entry point. Could it be default includes from node builtins? import require$$0$ ...

React Redux components are failing to render after changes are made to the state array

I'm fairly new to using React, Redux, and Thunk in my project. Right now, I'm facing an issue where I fetch an array from an API call in my action/reducer, but it doesn't re-render in the connected component/container that's hooked up t ...

exporting an enum from a typescript type definition file

As I compile the type definitions for a library that I'm utilizing, I came across one function that identifies the mouse button clicked by an integer: //index.d.ts export as namespace myLib; // activates the library listening for a specific mouse ...

A comprehensive guide on enabling visibility of a variable within the confines of a function scope

In the code snippet shown below, I am facing an issue with accessing the variable AoC in the scope of the function VectorTileLayer. The variable is declared but not defined within that scope. How can I access the variable AoC within the scope of VectorTile ...

Sorting elements in a 2-D array using Java's selection sort

As I prepare for an upcoming exam, I anticipate being tasked with arranging a two-dimensional array of integers. The goal is to have the smallest value at the top-left corner and the largest value at the bottom-right corner. My approach to this task invol ...

Hovering triggers the appearance of Particle JS

I am attempting to add particle js as the background for my website. I have tried implementing this code snippet: https://codepen.io/nikspatel/pen/aJGqpv My CSS includes: position: fixed; z-index: -10; in order to keep the particles fixed on the screen e ...

Display the number of objects in an array using Angular and render it on HTML

I am having trouble displaying the length of an array on my HTML page. No errors are showing up in the console either. Can someone help me figure out how to get the total number of heroes? HTML: <div *ngFor="let hero of heros"> <div>The tota ...

Error encountered in Angular NGRX while accessing the store: Trying to read property 'map' of an undefined variable

I have integrated NGRX effects into my Angular application and encountered the following error. I'm uncertain if I am using the selector correctly in my component to query the store? core.js:6162 ERROR TypeError: Cannot read property 'map' o ...

Identifying changes in Android volume settings via Progressive Web App (PWA)

After creating a PWA with React, I generated a TWA .apk using pwabuilder.com. While having a muted video playing on my screen, I am looking for a way to unmute the video when the user presses the volume change buttons on their Android mobile device. Is th ...

What is the trick to ensuring that the bind submit function always works consistently instead of sporadically?

I am attempting to compare two values (min - max) from two input fields. If the min value is greater than the max value, an alert message should be displayed... The issue arises when I correct the max value and submit again, as it continues to show the sa ...

When it comes to TypeScript, one can always rely on either event.target or event

I'm a beginner with TypeScript and currently in the process of refactoring an arrow function within React.js. Here is the current implementation: handleChange = (event): void => { const target = event.target || event.srcElement; this.s ...

What steps are involved in constructing Jodit from scratch?

Seeking a non-minified, readable version of Jodit, I attempted to build it myself. However, my lack of experience with composer, node, npm, webpack, TypeScript, and other tools has left me struggling. Is there anyone who can guide me through the process s ...

What is the process of defining a callback function in Typescript?

Here is a function that I am working with: .add({a: 1, b: 2}, function (msg, reply) { reply({z: msg.z}) }) I attempted something like this: interface SenecaMethods { add: (pattern: object, CALLBACK NEEDS TO BE INSERTED HERE) => object; } ...

Ways to expand the dimensions of a Popup while including text

I am using a bootstrap modal popup that contains a Treeview control in the body. The issue arises when the node's text width exceeds the popup's width, causing the text to overflow outside of the popup. Is there a way to dynamically adjust the ...

Issues stemming from cross-domain AJAX have resulted in errors with Karma and Jasmine

I've been working on configuring tests that utilize Jasmine and Karma to test my JavaScript code. Karma operates in Node.js and initiates a Chrome browser for testing purposes. Unfortunately, I keep encountering an error message that reads "Chrome 28 ...

What is the best way to incorporate Drift bot JS code into a static React NextJs application, such as a landing page?

I'm a beginner with ReactJS and I recently created a static website using ReactJS & NextJs. I decided to integrate a chatbot called 'Drift', but when following the installation instructions to insert JavaScript code in the <head> of HT ...

The absence of color gradations in the TypeScript definition of MUI5 createTheme is worth noting

Seeking to personalize my theme colors in MUI5 using TypeScript, I am utilizing the createTheme function. This function requires a palette entry in its argument object, which TypeScript specifies should be of type PaletteOptions: https://i.stack.imgur.com ...

Tips for utilizing buttons with the antd framework in Visual Studio Code

When using the Button and Input components from antd in vscode, I encountered an error specifically with the Button component and I am curious to understand why it is happening. Interestingly, when I tried using the Input component, it did not show any er ...

Utilizing inputRef in conjunction with MUI's useAutocomplete

Is there a way to pass the "inputRef" to Material UI's useAutocomplete? I'm looking to set a custom reference on the input, but the getInputProps() method from useAutocomplete already requires its own reference. I've attempted various appr ...