Updating an array of objects in JavaScript: A step-by-step guide

Let's start with a variable called data. It is an empty array of objects like this:

 
data = [
     {name:'a',value:'aa'},
     {name:'b',value:'bb'}
 ]

This data structure cannot be changed and begins with no values.

Our task is to update this data array using a function called updateData. Here's the initial setup of the function:

 
function updateData(){
     if(!data.length){
         data.push(arguments)
     }
     else{
         //this parts really confuse me
     }

 }

The goal of this function is to accept any number of arguments and apply certain rules for updating the data array:

  1. Update the object's value in the data array to match the argument's value if they share the same name.
  2. Add new arguments to the data array if none of the existing objects have the same name.

So, how should we implement this function?

 
updateData([
     {name:'a',value:'aa'},
     {name:'b',value:'bb'}
 ])
 // expect data = [
           {name:'a',value:'aa'},
           {name:'b',value:'bb'}
           ]

 updateData([
     {name:'a',value:'aa'},
     {name:'b',value:'DD'},
     {name:'c',value:'cc'}
] )
 // expect data = [
           {name:'a',value:'aa'},
           {name:'b',value:'DD'},
           {name:'c',value:'cc'}
           ]

Answer №1

Do you think this approach could work for your situation?

let info = [
     {label:'x',content:'xx'},
     {label:'y',content:'yy'}
 ];

 function updateInfo(obj){
  let isObjFound = false;
  for (let j = 0; j < info.length; j++) {
    if(obj.label === info[j].label){
      isObjFound = true;
      info[j].content = obj.content ;
    }
  }
  if(!isObjFound){
    info.push(obj)
  }
 }

Answer №2

Instead of using an array, consider using a name value pair as recommended by Ashutosh Upadhyay:

var data ={};

var updateData=function(){
  var len = arguments.length,
  i=0;
  for(i=0;i<len;i++){
    data[arguments[i].name]=arguments[i].value;
  }
};
updateData(
 {name:"a",value:"22"}, 
 {name:"b",value:"2"}, 
 {name:"c",value:"3"}, 
 {name:"a",value:"1"} // the updated value for 'a'
);
for(key in data){
  if(data.hasOwnProperty(key)){
    console.log(key + "=" + data[key]);
  }
}

If you must use an array, here's an alternative approach:

var data = [];
function findIndex(name){
  var i = 0;
  for(i=0;i<data.length;i++){
    if(data[i].name===name){
      return i;
    }
  }
  return i;
}
function updateData(){
  var i = 0;
  for(i=0;i<arguments.length;i++){
    data[findIndex(arguments[i].name)]=arguments[i];
  }
}
updateData(
 {name:"a",value:"22"}, 
 {name:"b",value:"2"}, 
 {name:"c",value:"3"}, 
 {name:"a",value:"1"} // the new value for 'a'
);

console.log(data);

Answer №3

If you want to ensure that names are unique, one approach is to define a data variable as a map and then add values using the name as the key:


var data={
    'a':'aa',
    'b':'bb'
}

function updateData() {
    for (var i=0; i<arguments.length; i++) { // Loop through each argument
        for (key in arguments[i]) { // Assign each pair (key,value) to the data map
            data[key] = arguments[i][key];
        }
    }
}

EDIT: Transforming function to create an array


function toArray() {
    var array = [];
    for (key in data) {
        array.push({name:key, value:data[key]});
    }
    return array;
}

Answer №4

Considering you're not concerned about the order of elements, opting for an object hash instead of an array could be a better choice. For example:

{
  'a': {name: 'a', value: 'aa'}
}

With this approach, searching based on keys is simplified and updating the hash becomes easier.

You can apply this technique to your specific scenario as well. Transform the array into a temporary object hash like shown above, make the necessary modifications, and then convert it back to an array. This method proves to be more efficient as it eliminates the need for searching through the entire array.

 var result_array = [];
 for (var key in object) {
   if (object.hasOwnProperty(key)) {
      result_array.push(object[key]);
   }
 }

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

Choosing the image that represents your website in Safari web previews

Every time I check iCloud.com on my Safari top sites, the thumbnail is always the same. I'm curious about how I can automate this for my own website. ...

Conceal the div element without revealing it beforehand

Is there a method to conceal a div without it initially loading? When I attempt to hide the div, it briefly appears for about 0.5 seconds before disappearing, which makes the animation look unattractive. Is there a way to prevent this, or am I approaching ...

Can we safely save a value in session storage directly from the main.js file in Vue?

Throughout the user session managed by Vuex, I have a session storage value set to false that needs to be monitored. Setting up this value directly from the main.js file looks like this: import { createApp } from 'vue'; import App from './Ap ...

What is the proper way to call a function in an HTML document?

I'm currently working on an HTML file that displays the coordinates provided by the user on a map. Every time I try to submit the form, I encounter an error saying "UncaughtReferenceError: NewMap is not defined." I've attempted using both externa ...

Executing all middleware within an express route

Currently, I am in the process of constructing an API using express and have implemented multiple middleware functions in my routes. One of the endpoints I am working on is displayed below: Router.route('/:id/documents') .get([isAuthenticated, ...

`Using top-level await in a module can interfere with the firing of the `onload` event

It seems that the load event is not triggering when I use await for an IndexedDB opening at the top level within an indirectly loaded module. Interestingly, if I remove the await, the load handler works as expected. Similarly, replacing the openDB call wi ...

Directing attention to a concealed element

I need help triggering a focus event after an element is recognized as focusable within the DOM. I have successfully shown form elements based on previous input, now I need to set focus for user input. Currently, the function provided is not working unle ...

Adding QML code into a Jade file

Currently working on developing a straightforward video streaming application using Node.js and integrating the WebChimera plugin. The player configuration is done in QML with Chimera, and I am facing numerous errors during the compilation process in Jade. ...

Error encountered: ReferenceError when using node.js, express, ejs, bcrypt,

Recently started diving into node.js and encountered an issue when trying to merge code from various projects. Everything was functioning smoothly until I switched the route path from '/dashboard' to '/store' along with the correspondin ...

Tips for swapping images as a webpage is scrolled [using HTML and JavaScript]

Hi there, I am looking to make some changes to a JavaScript code that will switch out a fixed image depending on the user's scrolling behavior. For example, when the page loads, the image should be displayed on the right side. As the user scrolls down ...

Is there a way for me to receive numerical values instead of NaN?

I'm currently facing a challenge in creating a Fibonacci number generator and I've hit a roadblock. It seems like I have a solution, but the appearance of NaN's is causing me some trouble. function fibonacciGenerator (n) { var output = [ ...

Exploring the concept of segmentation fault when using a fixed-size array of std::tuple within a class

For my image processing project, I needed to store three data points for each pixel in an image. To achieve this, I decided to use std::tuple within my CameraManager class: class CameraManager { private: static const int width_ = 700; static cons ...

What are the advantages of using classes versus ids for managing multiple li elements in example 20 with knockout and jQuery? Is one option more efficient and easier to maintain

<ul class="sellerDetails sellerdetailsData " data-bind="attr: { id: 'sellerdetailsData-' + $index()}"> <li><span class="buyerprocess-sprite seller-name"></span> <p class="leftfloat"> <span data-bind=" ...

Downloading multiple files on both iOS and Android devices

Is there a way to download assets (mp3/jpeg) in an Asynchronous manner? I have over 200 files in each case and the process is taking too long. Are there any techniques to speed up the download process on both iOS and Android? ...

The user ID variable has not been declared

After successfully retrieving the username from a link, I am facing difficulty in getting the user id back. While displaying the username works perfectly fine, I encounter an issue with fetching the userId when trying to populate the thumbnail - it shows " ...

Use javascript/ajax to create a dynamic dropdown menu

I have successfully retrieved data from an ajax and JSON request on another php page. Using json parse, I was able to extract two array strings. JAVASCRIPT: if (xmlhttp.readyState==4 && xmlhttp.status==20 { var data = JSON.parse(xmlhttp.respon ...

Error message: NGINX combined with Express.js and socket.io, page not found

I currently have a node/express.js/socket.io application set up on an Ubuntu Server running on port 3002. I've made sure to open all ports on the machine for accessibility. When accessing the app directly at 11.111.111.1:3002/, everything runs smooth ...

Why does my array become empty once it exits the useEffect scope?

const [allJobs, setAllJobs] = useState([]); useEffect(() => { axios.get('http://localhost:3002/api/jobs') .then(res => setAllJobs(res.data)); allJobs.map((job, i) => { if (job.language.toLowerCas ...

Encountering a JavaScript problem in Google Chrome?

Something strange is happening when I try to place an image in the canvas... "Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideo ...

reconstructing the JSON array

// Here is an initial JSON object to work with var originalJson = { "rows": [{ "ID": 123, "Data": 430910, "VersionNum": 0, "RowSeqNum": 1, "IterationNum": 1, "FirstName": "Aqwemara", "LastName": "Seweqweebi", "Location": " ...