Finding a specific item in an array and swapping it out with a different object - but how?

Here is an array for reference:

[
  {color: "blue"}, 
  {color: "red", size: "large"}, 
  {color: "green", size: "medium"}
]

My task is to:

  1. Locate the object with a color of green
  2. Substitute that object with
    {color: "green", size: "x-large"}

Answer №1

If you want to update an object in an array, use the find function to locate the object and then make your modifications.

var arr = [{color: "blue"}, {color: "red", size: "large"}, {color: "green", size: "medium"}],
    result = arr.find(({color}) => color === 'green');

if (result) result.size = 'x-large';

console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Utilizing the map method on an array will generate a new array.

The essence of the map() method lies in creating a fresh array by invoking a specified function on each element within the original array.

const arr= [
  {color: "blue"}, 
  {color: "red", size: "large"}, 
  {color: "green", size: "medium"}
];


let result = arr.map(obj=>{
 return obj.color=='green'? {color: "green", size: "x-large"}:obj;
})

console.log(result)

You also have the option to employ the find functionality.

Upon using the find() method, you'll retrieve the initial array element that meets the criteria set by a given testing function. In cases where no match is found, undefined gets returned.

DEMO

const arr = [{
  color: "blue"
}, {
  color: "red",
  size: "large"
}, {
  color: "green",
  size: "medium"
}];

let result = arr.find(v => v.color == 'green');

if (result) {
  result.size = 'x-large';
}
console.log(arr)

Answer №3

To update an item in an existing object, you can loop through it using forEach and check for a specific condition. If you need to create a new array based on the original one, you can utilize the map function instead.

var oldObj = [{
    color: "blue"
  },
  {
    color: "red",
    size: "large"
  },
  {
    color: "green",
    size: "medium"
  }
]
oldObj.forEach(function(item) {
  if (item.color === 'green') {
    item.size = 'x-medium';
  }
});
console.log(oldObj)

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

Is there a way to automatically navigate to the accounting dashboard once the extract import is complete?

In the Odoo accounting module, you have the option to import bank statements. After the import is completed, it automatically takes you to the reconciliation view, but I am looking to redirect it to the accounting dashboard. Upon further inspection, I dis ...

Issues with MC-Cordova-Plugin on Ionic and Angular Setup

Recently, I integrated a plugin for Ionic from this repository: https://github.com/salesforce-marketingcloud/MC-Cordova-Plugin After successfully configuring it for iOS, I encountered difficulties on Android where the plugin seems to be non-existent. It ...

Tips for transferring an array from a php page to a javascript page

In my PHP code, I have an array structured like this: 1) <body onload="addMarkers(<?php print_r($myArray) ?>)"> 2) <body onload="addMarkers(<?php echo json_encode($myArray) ?>)"> Unfortunately, these attempts were unsuccessful. U ...

What is the best way to compare dates in an array using PHP?

Within an array, I have datetime inputs ranging from 8am to 5pm. 2022-09-23 08:00:00 2022-09-23 08:30:00 2022-09-23 09:00:00 2022-09-23 09:30:00 2022-09-23 10:00:00 2022-09-23 10:30:00 2022-09-23 11:00:00 2022-09-23 13:00:00 2022-09-23 13:30:00 2022-09-23 ...

Add a plethora of images to the canvas

Just starting out with Fabric.js and trying to figure out how to draw a picture on the canvas after a drop event. I managed to do it once, but am struggling with inserting more pictures onto the canvas (each new drop event replaces the previous picture). ...

Submitting form based on HTML select input issue

I am facing an issue with a select form where the value resets to "10" every time I send the form. Is there a way to keep the selected option, for example "20", after submitting the form? Below is the code snippet: <form method='get' name=&a ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

Can we condense the code to create a more concise and efficient function?

Can someone help me refactor this code snippet below into a function and combine the two IF statements? Many thanks! let value = productDetails.recentPurchaseDate; if (!productDetails.salesPrice && !productDetails.recentPurchaseDate) { value = false; } ...

Having trouble with the find method when trying to use it with the transform

In my code, I have three div elements with different values of the transform property assigned to them. I store these elements in a variable using the getElementsByClassName method and then try to find the element where the value of the transform property ...

Discovering the unique identifier of an item in Node.js is simple with these steps

I have a delete API which requires the item's unique ID to be passed in for deletion. How can I capture the ID of the item being deleted and send it to the API? Here is the API: app.post("/delete_product", function (req, res) { var data = { ...

Saturn's Rings - beginning circumstances

Currently, I am developing a simulation of the Saturn system that will enable users to manipulate variables such as increasing the mass of its largest moon, Titan, to match that of Earth. This adjustment will illustrate how other moons and rings are affect ...

Struggling to find a solution for changing the color of a select box when an option is chosen

Here's an example of the HTML I'm working with: <select onclick="colorchanger()"> <option name="white" value="0">--Select--</option> <option name="red" value="1">Work</option> <option name="green" value="2" ...

Click on a button to send the React Router path as a parameter in

I've got a React form with a submission button like this: <Link className="btn btn-secondary btn-width-200 search-submit" to={{pathname: '/booking/search', query: this.state.filters}}> Search </Link> Within the ...

Running into issues on Heroku with Node, Gulp, and Browserify: Module Not Found Error

My asset building process relies on Gulp. Specifically for Javascript, I have a task set up with Browserify to handle all code dependencies. While everything runs smoothly locally, deploying to Heroku results in a Gulp failure with the following error: 2 ...

Is there a way to horizontally center Material UI Switch and its icon props?

I'm using Material-UI to implement a Switch component on my project. This particular component allows for the addition of icons, however, I've encountered an issue with alignment when including them. Is there a way to horizontally center align b ...

What is the most effective method to guarantee the creation of an object prior to navigating through the code that relies on it?

I recently encountered an issue with my code that utilizes fetch() to retrieve and convert .tiff images into an html5 canvas for display in a browser using tiff.js (https://github.com/seikichi/tiff.js/tree/master). While the functionality mostly works as i ...

A dynamic input field will appear on the page following the closing </form> tag

I encountered an unusual situation where upon clicking a button with the id #fusk, dynamic elements are added. Here is the code snippet: $('#imgc').append( "<div class='divi'>" + "<input type='hidden' name=' ...

What are some ways to track the loading progress of a JSON file retrieved through an Axios call?

To track progress accurately, I am contemplating implementing the following steps while making an axios call: Retrieve file size during the json file request Determine the percentage of downloaded file size from the network tab Currently, I only have a ...

The Ajax Get Request functions properly when called in a browser, but returns a 302 error when executed within an iframe. What might be causing this discrepancy?

I am currently developing a web application that initiates multiple ajax requests upon startup. The app functions perfectly when executed independently in the browser. However, when I run it within an iframe, one of the ajax requests unexpectedly returns ...

What is the best way to display a series of interconnected tables in a specific order within MySQL using recursion?

Given: table dependencies listed in sequence (Generated by MySQL Forward Engineer script) tableA, NULL tableB, NULL tableB, tableA tableC, NULL tableC, tableA tableD, NULL tableD, tableC I am working with a MySQL database containing over 40 relational tab ...