Exploring ways to compare and update values in an array of objects using JavaScript

I have a situation where I need to compare the names and values of two arrays filled with objects.

const array1 = [
  {
    name: 'Sarah',
    value: null
  },
  {
    name: 'Michael',
    value: null
  }
]

const array2 = [
  {
    name: 'Sarah',
    value: '1'
  }
]

If the object's name property in array2 is found in array1, then update the value of the name to '0', otherwise leave it unchanged.

The desired outcome should be :

[
  {
    "name": "Sarah",
    "value": "0"
  },
  {
    "name": "Michael",
    "value": null
]

Could someone please provide guidance on how to achieve this?

Answer №1

If you are looking to update values in one array based on another, you can achieve this using two separate forEach() loops:

const firstArray = [
  {
    name: 'Alice',
    value: null
  },
  {
    name: 'Bob',
    value: null
  },
  {
    name: 'Charlie',
    value: null
  }
]

const secondArray = [
  {
    name: 'Alice',
    value: '1'
  },
  {
    name: 'Charlie',
    value: '2'
  }
]

secondArray.forEach((item) => {
  firstArray.forEach((element) => {
     if(element.name === item.name){
       element.value = item.value;
     }
  });
});
console.log(firstArray);

Answer №2

Here is the straightforward solution:

Let's iterate through each item in array1 and compare it with each item in array2. If we find a match based on name, we will set the value of record1 to "0".

Answer №3

You can implement a solution by applying the map function to the first array and then using the find method. Keep in mind that this approach ensures that the original content of array1 remains unchanged.

const array1 = [
  {
    name: 'Alice',
    value: null
  },
  {
    name: 'Bob',
    value: null
  }
];

const array2 = [
  {
    name: 'Alice',
    value: '1'
  }
];

const updatedArray = array1.map(item1 => {
  const newItem = { ...item1 };
  if (array2.find(item2 => item2.name === item1.name)) {
    newItem.value = 1;
  }
  return newItem;
});

console.log(updatedArray);

Answer №4

It's quite straightforward:

Below is the code snippet you can utilize:

array2.forEach(
                function(parent){

                    array1.find(function(child)
                    {
                        if(child.name==parent.name){
                            child.value=0;

                        }
                    })

                    }

);

Answer №5

Give this a shot:

const listOne = [
{
    name: 'Sarah',
    number: null
},
{
    name: 'Emily',
    number: null
},
{
    name: 'Brandon',
    number: null
}
]

const listTwo = [
{
    name: 'Sarah',
    number: '0'
},
{
    name: 'Brandon',
    number: '0'
}
]


var updatedList = listOne.map(item => {
    if(listTwo.some(function (entry) { return entry.name === item.name })){
        item.number = 0;
    }
    return item;
})

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, facing the challenge of preserving stored data in localStorage while accounting for the impact of useEffect upon

Seeking some assistance with the useEffect() hook in my Taking Notes App. I've set up two separate useEffects to ensure data persistence: one for when the page first loads or refreshes, and another for when a new note is added. I've added some l ...

The focus is being lost on the ng-model when used within an ng-repeat

Within my JavaScript code, I am initiating a new question object like this: $scope.newQuestion = { answers: [] }; This is how it reflects in the HTML: <div class="row" ng-repeat="answer in newQuestion.answers"> <div class="input-field col m ...

Display a progress bar on the index page of the grid view

Seeking assistance in displaying a progress bar on the grid view page index. Currently, I have successfully implemented a progress bar on button click and would like to replicate this functionality when the user switches from 1 to 2. Here is the modal pop- ...

What could be causing the javascript slidetoggle function to keep closing?

I have a link on a page that toggles the search form on and off. Let's say you search for Spring term classes, then you want to search for a new term and click "Start a new Search." The link works great and toggles just fine...BUT the toggle automatic ...

Accessing an array beyond its callback scope

Currently, I am working on creating an array of objects with different key values by utilizing basic web scraping techniques in NodeJS. One challenge I am facing is accessing the 'built' Array outside of its parent function, which you can find he ...

Troubleshooting issues with $scope in an Angular Schema Form modal

Plunker This Plunker demo allows for editing rows in a grid. A new method has been implemented based on RowEditCtrl to insert a new row, but there are issues with validation. Upon inserting a new row, the form initially appears as "pristine and valid". T ...

Enhance user interface dynamically with additional components in ReactJS by rendering them onClick. Master the optimal

Just started using React and I'm really enjoying it. I have a scenario where the parent component renders both: A TagBuilderContainer (which contains initially 1 TagBuilderComponent) An "Add Tag" button with an onClick event (intended to add a new ...

When passing parameters as an array in PHP, remember to use "[ ]"

My function receives parameters as an array: public myFunction($options = array("option1"=>true, "option2"=>true, "option4"=>"astring"), $anotherparameter = 0) { if($options["option1"] === true) { //Perform all the necessary operatio ...

What is the best way to organize large amounts of data into an array?

I am currently working on developing a unique version of wordle using javascript and html. In order to do this, I require a comprehensive list of all possible wordle words stored in an array format. Although I have the words listed within a document contai ...

What could be causing the jQuery .load() function to trigger twice?

While using jQuery 1.4 along with jQuery History, I noticed that Firebug/Web Inspector are displaying 2 XHR GET requests on each page load (which doubles when visiting the homepage (/ or /#). For example, if you visit this or any other page with Firebug e ...

The webpack development server refreshes the page just one time

I've been searching through various issues on Stack Overflow but haven't had any luck. It seems like most solutions are for an older version of webpack-dev-server. Despite trying numerous things, my app just won't reload or rebuild more tha ...

Accessing data from localhost using Vue.js and Axios is restricted due to CORS policy and the error "Access to XMLHttpRequest" may be

Having a minor issue... Trying to retrieve a basic json file from my server for testing purposes (not an actual API). Utilizing VueJS and axios. Here is my code : getServicesAPI() { axios.get("http://51.91..../dist/API/Services.json").the ...

Struggling to understand the concept of utilizing Promises for data retrieval

I'm currently facing an issue with my async function that awaits a GraphQL call. Even though the call returns a Promise containing the desired data, I'm struggling to access it effectively. Below is the snippet of code in question: export async ...

Approach for calculating the total of values during an iteration

I am working with the array $scope.otherDetailsData [0] object amount: 29.9 code: "012" currency: "BRL" payedDate: "2016-11-10" roDate: "2016-08-01" type:"OTHER" [1] object amount: 39.9 code: "013" currency: "BRL" payedDate: "2016-11-11" roDate: "2016- ...

Is it possible to remove the "disabled" attribute using JS, but the button remains disabled?

There are two buttons on my page: the first one is currently disabled, and the second one is supposed to enable the first button. That's the plan. Button 1: $(document).ready(function() { $('#click').click(function() { document.getE ...

What could be the reason my code isn't successfully performing addition within the input field?

As a novice, I am practicing by attempting to retrieve a number from a text field, prompting the user to click a button that adds 2 to that number, and then displaying the result through HTML. However, I keep encountering an issue where NaN is returned whe ...

Is it possible to deinitialize data tables (remove from memory)?

I'm currently utilizing data-tables (with jQuery) on my website. The particular data-table I have implemented seems to be consuming excessive memory in javascript, causing a slowdown in other functionalities. Is there a way for me to de-initialize th ...

Using the setTimeout function is essential for successfully extracting values in a Jquery each loop. Without

I created a loop to adjust the padding on an image tag placed atop another image. Strangely, it was only capturing the first one or two values until I added a setTimeout function, which seemed to fix the issue. Below is the jQuery code: $(document).ready ...

"Revolutionize real-time data updates with Node.js, Redis, and Socket

Greetings! I am currently working on a project for my school that involves creating a "Twitter clone." My goal is to incorporate a publish subscribe pattern in order to facilitate real-time updates. One key feature users will have access to is the abili ...

Utilize styled-components in next.js to import and resize .svg files seamlessly

I have been attempting to import .svg files into my next.js project, but I have not had any success. I tried importing the .svg files the same way as in my React project by creating a typing.d.ts file and importing the svg as a component. However, it did ...