``Is it possible to iterate through a collection of objects using a loop?

I am facing an issue with updating a global array that contains objects, where each object includes another array. My goal is to update the main array with values from the arrays within the objects following a specific logic!

generalArray = [{name:String, features:String[]}]

// Here's the code snippet
let array1 = [{ name: "num", features: ['id']  },
            { name: "cat", features: ['gender'] }];
ob = {name:'num2', features:['id']};

function updateArr(arr, ob) {

  const index = arr.findIndex(x => 
      ob.features.toString() === x.features.toString()
                              );
    if (index === -1) {
        arr.push(ob);
    } else {
        arr[index] = ob;
    }
}
console.log(array1);
updateArr(array1, ob);
console.log(array1);

The current solution works flawlessly when each object's 'features' array contains only one string. However, it encounters an issue when an 'features' array includes more than one string. For example, if 'features'=['id','gender'], the function fails to perform as expected. Any assistance would be greatly appreciated! Thank you.

Answer №1

I have devised a solution to address the issue you are facing

var array1 = [{ name: "num", features: ['id', 'gender']},
            { name: "cat", features: ['gender']}];
ob = {name:'num2', features:['id']};

function updateArray(arr, obj){
  for(var i = 0;i < arr.length; i++) {
    if(obj.features.join("") === arr[i].features.join("")) {
      arr[i] = obj;
      return;
    }
  }
  arr.push(obj);
}

updateArray(array1, ob);
console.log(array1);

Answer №2

Choice 1: When the order of elements in the features array is not important.

To compare, you can modify the following line of code:

ob.features.toString() === x.features.toString()

to

JSON.stringify(ob.features.sort()) === JSON.stringify(x.features.sort())

Choice 2: If the order of elements in the features array does matter, simply omit .sort().

Note: If you prefer not to use stringify, you can utilize the array comparison function provided in this answer - .

Answer №3

let arr1 = [{ title: "item", attributes: ['height'] },
            { title: 'object', attributes: ['size'] }];
obj = {title:'item2', attributes:['height']};

function updateArray(arr,obj){

  const ind = arr.findIndex(x =>
  obj.attributes.includes(x.attributes)
                              );
                              debugger
    if (ind === -1) {
        arr.push(obj);
    } else {
        arr[ind] = obj;
    }
}
console.log(arr1);
updateArray(arr1,obj);
console.log(arr1);

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

PHP Instant Chat Improvements

I am in the process of developing a messaging system that consists of the following components: A form that allows users to send messages, with PHP handling the insertion of data into a MySQL Table named userMessages upon submission. A PHP page that ...

Encountering an error when integrating my library with MUI

Currently, I am working on developing a library that wraps MUI. One of the components I created is a Button, and here is the code snippet for it: import React, { ReactNode } from 'react' import Button from '@mui/material/Button'; impor ...

Establish individual states for every dynamically created component using the same handler function

I have a component in React built with Material UI, where the child component (Paper) is dynamically generated depending on the number of items in an array. The challenge I'm facing is changing the elevation property of the Paper component when it&ap ...

Ways to reach component method via router

When making an Ajax request and displaying the data in a table component, I encounter an issue where I need to extract the clicked data for use in another Ajax request within a different component that is called through React-Router. The challenge lies in ...

Refactor the fat arrow function in Typescript to maintain the bare function signature verification

When using AOT in Angular, it is necessary to rewrite all functions and reducers to not utilize arrow functions: An error occurred: Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function o ...

Revamp the style of the date field in a Material UI dialog

I'm currently working on a React project where I am using Material-UI's date picker component to display date items. However, I find that the default style does not meet my requirements. I would like to use a selector for displaying dates in the ...

Having trouble launching simple ionic template: Issue with locating module 'fast-deep-equal'

Recently I started using Ionic and followed the steps to install the basic blank template as shown below. First, I installed Ionic and Cordova by running the command: npm install -g ionic Cordova. After that, I created my first Ionic project using the f ...

Is there a Wordpress floating bar similar to the one seen on 9gag?

After browsing through some posts on stackoverflow, I noticed that my website is not responding as expected. You can check out my site here: To troubleshoot, you can examine the source code and utilize Firebug to inspect the css and javascript being used ...

Change the background color of mat-select to match the selected mat-option

<mat-form-field> <mat-select [formControlName]="name"> <mat-option [value]="option.id" [ngStyle]="{backgroundColor: option.color}" *ngFor="let option of list; let i = index" ...

What is the best way to update the state by either adding to it or replacing it if the key

I'm currently working on a project involving radio buttons and I need to create dynamic state by setting the initial state on the first click, then updating it with subsequent clicks by either concatenating the new value onto the existing state or rep ...

JavaScript Regular Expression Assistance Domain Snatcher

I am in the process of developing a JavaScript Regex and I am struggling to find the right pattern to match a specific domain. Let me provide an example for better understanding. I need a regex that can identify any domain that exclusively contains (text. ...

Updating a hyperlink with data dynamically upon clicking a different button using jQuery

I need to create a script that will add the id of 'peter' to the hyperlink of anchor 'jack' when 'peter' is clicked. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery. ...

Handling error reporting using JSON in jQuery AJAX post success

UPDATE: I have resolved the PHP errors mentioned in previous Answers, however, the issue still persists. I am attempting to implement an error message display in case of a failed POST request and a success message for successfully completed requests. Curr ...

Creating resizable rows of DIVs using jQuery

I'm currently developing a scheduling widget concept. The main idea is to create a row of DIVs for each day of the week. Every row consists of a set number of time periods represented by DIVs. My goal is to enable the resizing of each DIV by dragging ...

Retrieve the place_id associated with the address components

Having trouble obtaining the place_id of address_components using Google place autocomplete? The JSON data only includes long_name, short_name, and types. Take a look at my code snippet below: var object_location = document.getElementById('object_loc ...

The addition of an asynchronous call caused Array.map to start experiencing errors

I am working on a React component that iterates through an array of messages and renders JSX based on certain conditions: messages.map(async (msg) => { let previewImage: URL | undefined = undefined; if (msg.mediaId) { previewImage = await stora ...

We regret to inform you that the request cannot be processed by our Express

Currently, I am in the process of learning nodejs and expressjs and attempting to integrate it into the Spring MVC pattern. My intention behind this is to maintain cohesion within my files. However, the results are not quite aligning with my expectations.. ...

The issue of jQuery, Ajax, and MVC6 parameters becoming null after an Ajax request has been identified

Hello everyone, I am a beginner in asp.net core, c# and MVC 6. Currently, I am facing an issue with sending data over ajax to my controller. function sendAjaxData() { $.ajax({ url: "AjaxWithData", // using hardcoded value for testing purpose type ...

Move information from one webpage to a different page

After developing a site using NextJs, I successfully integrated Discord login functionality and was able to retrieve the user's guilds in the oauth file. Now, I am looking to send this list of guilds (in JSON format) to my dashboard page. In the oau ...

What are the steps to compile Sencha Touch using sencha-touch.jsb3?

I've been working on modifying the bundled sencha-touch.jsb3 file in an effort to decrease the size of the framework code. Here's what I've done so far: First, I downloaded the Sencha SDK Tools from I then made edits to SenchaTouch/sen ...