``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

Angular and ngrx are experiencing an issue involving an infinite loop within a selector

Is it possible to dispatch an action within a selector in a single store? this.store$.pipe(select(selectPersonByName, {personSelectorProps: this.id[]0})) .subscribe(history => { this.store$.dispatch(selectAssignWorkHisto ...

Issue with RequireJS: The data-main attribute fails to load the specified file

As I convert my small project into nodejs, I am facing an issue with the requireJS file that defines the JS to be used in the project not loading properly. Below is the structure of my project: https://i.sstatic.net/oYnqn.png The ng-app specifies the fr ...

Set the height of a div based on the height of another div

My challenge involves a textarea that dynamically expands as content is added to it. The structure of the textarea within a div element is illustrated below: <div id='sendMes' class='container-fluid'> <form action='#&apos ...

How can I fix the issue of clearInterval not functioning properly in an Electron JS application?

The clearInterval function is not working properly in this code. What can be done to fix this issue? var inter; ipcMain.on("start-stop",(err,data)=>{ console.log(data.data) function start(){ inter = setInterval(fu ...

Has Angular been assimilated into the window object by webpack?

I'm encountering a puzzling issue with webpack that I can't seem to resolve. Here is the link to my webpack.config file: https://github.com/saike/maluvich-browser/blob/master/webpack.config.babel.js In my project, I import angular using ES6 mo ...

Incorporate new content into a jquery mobile listview on the fly

I'm attempting to use JavaScript to dynamically populate a listview with items. Here is the code I have written: //Function to load data fields for items dynamically function initialiseFields(listViewId){ for(var i = 0; i < 10; i++){ ...

Bring in the SCSS directory from the overarching SCSS program

I am currently working with Angular (Jhipster) in my application and I am looking to include multiple .scss files in my global.scss file. To achieve this, I have created a folder called "util" at the same level as the global.scss file and placed these .scs ...

Feeling lost with the concept of getcontext in js/ts and uncertain about how to navigate through it

Recently, I've been encountering undefined errors in my browser and can't seem to figure out how to resolve them. It seems that the usage of the keyword "this" in JavaScript and even TypeScript is causing quite a bit of confusion for me. Let&apo ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...

Controlled Material-UI v5 DateTimePicker triggers input focus upon closure

Is there a way to have 2 DateTimePicker components as siblings, and when I click on the second one while the first one is still open, it should open a new DateTimePicker with focus on it? Can someone help me achieve this? Link to code example I want the ...

Refreshing/Redrawing/Resizing a panel in jQuery Layout when toggling the visibility of a header or footer

Currently utilizing a standard jQuery layout with north, south, west, east, and center sections as outlined in the documentation. In both the west and center panels, there are header and footer panes included. While everything is functioning correctly, I ...

Accessing JSON Data Using JQUERY

Currently, I am experimenting with grabbing JSON data from websites using the $.getJSON() method. Here is the code snippet I have been working on: The website I am attempting to retrieve JSON data from can be found here. Interestingly, the code functions ...

Ensure that you accurately maintain object ids following the creation of elements using ng-repeat

I have a set of items listed with unique objects within my controller $scope.itemsList = [ {"id": 0, "item": "sw", "category": 'A' }, {"id": 1, "item": "mlr", "category": 'B'}, {"id": 2, "item": "lvm", "category": 'C&a ...

Should the button be eliminated in favor of simply requesting input from the user?

Looking for help with my code. How can I set it up so that when the HTML file is clicked on, it prompts for input instead of displaying a button? I'm new to coding and could use some guidance. <!doctype html> <html> <head> <meta ...

The RxJs 'from' function is currently producing an Observable that is unrecognized

import { Tenant } from './tenant'; import { from, Observable } from 'rxjs'; export const testTenants: Tenant[] = [ { 'tenant_id': 'ID1' } ] const tenants$: Observable<Tenant>= from(testTenant ...

Exploring the Angular Checkbox n-Change - is it really all about 'this'?

Looking for a solution with a series of checkboxes: <input type="checkbox" ng-change="??????"> I am trying to figure out how to set $scope.mode.someOtherValue = false when the checkbox is checked. Any ideas on how to extract the checkbox value wi ...

JavaScript encountered a problem when trying to call the inline function

I created a function called controls that adds HTML elements dynamically into the specified div. function controls() { var block = $('#controls'); block.html(''); block.append('<button type="button" onClick="f ...

Gain access to the "computed style" of elements in a directive

I recently created a directive for a loader element, but I am facing issues with undefined styles. Is there a way to access the "computed styles" of an element within the directive? export const ElementLoader = { componentUpdated(el, binding) { if ...

Having issues with contenteditable functionality not functioning properly on elements that are dynamically generated

Creating an unordered list dynamically and adding items to it on a button click. Appending it to a section with contenteditable set to true, but encountering issues. The code snippet below demonstrates the process: // Create text input var categoryInput = ...

Construct a div element using JSON information

I am retrieving information from a database and organizing it into a JSON array. Here is the data that I have: [{"id":"0","name":"red","percentage":"60"},{"id":"1","name":"blue","percentage":"58"},{"id":"4","name":"green","percentage":"12"}] The structu ...