How can I modify certain attributes within an array of objects?

https://i.sstatic.net/TKkcV.jpgI need help with updating properties within an object array. Below is my code for reference. I have an object array consisting of two arrays, where the first one contains attribute "first" and the second one contains "last". When a specific name (either first or last) is clicked on, the function will loop through the object array and update the value of the matching property (tempFirst, tempLast). Although I've only declared it within the onHandle function here, in my actual project, I'm passing these parameters.

For example: if (first === first), then change the value of that property.

import logo from './logo.svg';
import './App.css';
import React, { Component } from 'react';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      objectTemp: []
    };
  }

  componentDidMount(){
    let objectArray = [
      {
        name: "hello",
        first: 77
      },
      {
        name: "world",
        last: 66
      },
    ]

    this.setState({
      objectTemp: objectArray
    })
  }

  onHandle = () => {
    let tempFirst = "first";
    let tempLast = "last";

    let storeState = [...this.state.objectTemp];
    
// Here I want to check if either tempFirst or tempLast is equal to the property in the object array
    for(let i = 0; i < storeState.length; i++){
      //if(storeState[i] === tempLast){
        console.log(...storeState[i]);
      //}
    }
  }

  render() {
    console.log(this.state);
    return <button onClick={this.onHandle}>VIEW</button>;
  }
}

export default App;

Answer №1

Here's the suggested step for making your modification:

handleModification = (name: string, data: any) => {
    /// Adjust your information:
    const modifiedData = this.state.dataList.map( element => {
         /// Check and update data if condition is met
         if(element.name === name){
             element.data = data;
         }
         return element;
    })

    /// Update state with new data
    this.setState({dataList: modifiedData})
}

Answer №2

To transition from the previous state to a new state, you can compare each element object with a designated "searchKey" and update the value if there is a match.

Take a look at this onHandle function which iterates through the objectTemp state and generates an array of object entries (key-value pairs). It then consolidates the array back into an object, while verifying the keys for any matches.

onHandle = (searchKey, newValue) => {
  this.setState(prevState => ({
    // Mapping the previous state to the next state
    // [obj1, obj2, ...objN]
    objectTemp: prevState.objectTemp.map(obj => {
      // Generating an array of entries and consolidating them into an object
      // [[key1, value1], [key2, value2], ...[keyN, valueN]]
      return Object.entries(obj).reduce((obj, [key]) => {
        // If key matches search key, create a new object with updated value,
        // otherwise maintain existing object
        return key === searchKey
          ? {
            ...obj,
            [key]: newValue
          }
          : obj;
      }, obj);
    })
  }))
}

See it in Action

https://codesandbox.io/s/late-sun-r7u1v?expanddevtools=1&fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js&theme=dark

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

Tips for transforming every element of an array into its own array using JavaScript or Loadash

Hello, I have an array that looks like this. I am attempting to convert each element into its own array. I tried using lodash's chunk function but was unsuccessful. [ 'Product 1', 'Product 2', 'Product 3', 'Product ...

Passing a leading zero function as an argument in JavaScript

Is there a method for JavaScript to interpret leading zeros as arguments (with the primitive value as number)? I currently have this code: let noLeadingZero = (number) => { return number } console.log('noLeadingZero(00):', noLeadin ...

Merging several Excel spreadsheets into one Excel spreadsheet using Node.js

I have been attempting to upload 4 files, each of size 391 MB, to a node server. My goal is to receive a single file from the server that contains a merge of all 4 uploaded files. However, despite receiving a response from the server, I am not getting the ...

Optimizing CSS to eliminate extra space from the first button in the navigation menu bar

I'm currently working on creating a simple CSS-based navigation bar, but I've encountered an issue. The first item in my HTML list seems to have extra space to its left that I can't seem to remove. Check out the live example here Also avai ...

I am unable to view the most recent version of json-parse-better-errors on NPM

I've encountered an issue while trying to execute the npx create-react-app command on my local machine. The script fails during the installation process of json-parse-better-errors. It seems like it is looking for version 1.0.2, which is stated as the ...

How can I eliminate the border appearance from a textfield fieldset component in Material-UI?

I have been struggling to remove the border using CSS code I found on Stack Overflow, but unfortunately, the issue persists. If anyone could kindly assist me in fixing this problem, I would be extremely grateful. Can someone please advise me on the specif ...

Retain the user's input in the text box even after the form has been submitted

Currently, I am tackling the challenge of creating a register form with an error handler to manage any mistakes made by users during registration. Once the form is submitted, potential errors are displayed to the user. To enhance user experience, I am ex ...

When using jQuery to select elements of a specific class, make sure to exclude the element that triggered the

A dynamic number of divs are generated from a data source. Each div contains an image button and another div with text. While the actual scenario is more complex, we can present a simplified version: <div id="main"> <div id="content_block_1" ...

The type '{ domain: any; domainDispatch: React.Dispatch<any>; }' cannot be assigned to a type 'string'

Within my codebase, I am encountering an issue with a small file structured as follows: import React, { createContext, useContext, useReducer } from 'react' const initState = '' const DomainContext = createContext(initState) export co ...

Error encountered: npm encountered an unexpected end of JSON input while parsing, near '...ersion: OpenPGP.js v3'. This issue is arising during the installation of create-react-app and is causing the process to abort

Encountered npm ERR! Unexpected end of JSON input near '...ersion: OpenPGP.js v3' error during create-react-app installation. https://i.stack.imgur.com/xZS8b.png ...

How can I make all fields in the CKAN Resource form html the same size as the "Description" field?

I am completely new to CKAN and front-end development. I've been scouring through various html/css files without success in locating where I can adjust the field sizes in the resources form (where users can modify metadata via GUI). I would like to r ...

What causes the error message 'avoid pushing route with duplicate key' when using NavigationStateUtils in React Native?

Within my React Native + Redux project, I have set up a reducer for navigation utilizing NavigationStateUtils: import { PUSH_ROUTE, POP_ROUTE } from '../Constants/ActionTypes' import { NavigationExperimental } from 'react-native' impo ...

Saving file with HTML download button results in only HTML document being saved

I am attempting to include a "download file" button on my gatsby website as shown below: <a href="../../images/project-logos/placeholder-company-logo.png" download="test" className="responsive-square project-logo" > <img sr ...

The functionality of Bootstrap Tabs is compromised when used within a jQuery-UI dialog window

My goal is to develop a user interface similar to MDI for my application. To achieve this, I am utilizing the dialog feature of the jQuery UI library. To dynamically create a dialog window on demand, I have coded a helper function as shown below: functio ...

How can the CSP nonce be implemented?

Lately, I've been diving deep into the world of CSP (Content Security Policy), but I've hit a roadblock when it comes to understanding how nonces actually work. My main concern is avoiding the use of "unsafe-inline" for security reasons. From wh ...

The save feature becomes dysfunctional after switching to the Material-UI dependency in a React project

After integrating the Material-UI dependency into my ReactJS code, I encountered an issue where the "save" functionality no longer works properly. Previously, when editing a task in my simple Todo list app, the new name would be saved successfully. However ...

How can I transfer data from two queries to Jade using Node.js (Express.js)?

I have a database with two tables - one for storing user information and another for managing friendship connections: setting up a friend list in mysql My goal is to create a profile page using Jade, specifically profile.jade: - each user in users ...

Enhance the efficiency of traversing a lengthy list of comparisons within an array.filter method

I am struggling with finding an efficient method to filter out items from an array of objects based on two specific attributes matching those of the last 6 items of another array. Currently, I have a manual process in place which results in cumbersome and ...

JavaScript queries in Selenium WebDriver

Lately, I have been using the selenium webdriver (nodejs module) along with mocha for writing automation tests, and encountered a few challenges along the way. Issue with Scrolling driver.findElement() seems to return false as it is unable to find the e ...

Error encountered in Webpack 4 when trying to compile node modules CSS file: Unexpected .(dot) token

I am currently in the process of transitioning my React project from client-side rendering to server-side rendering. Unfortunately, I have encountered an issue with my webpack configuration for CSS that was working perfectly fine in my original project (c ...