Traverse through an object and set a value to an array of objects only when specific criteria are satisfied - vanilla JavaScript

Consider having an object structured as shown below, with multiple items:

myObject:{
 item1: {
  visible: true;
 },
 item2: {
  visible: true;
 },
 item3: {
  visible: false;
 },
}

Additionally, there is an array of objects as follows, with potentially numerous items:

var objs = [ 
    { name: 'item1', visible: false },
    { name: 'item2', visible: false },
    { name: 'item3', visible: false }
];

The challenge is to loop through the object and update the visibility in the array only if the identifiers match. For instance, when item1's visibility is false in the object, it must also be updated in the corresponding item1 within the array.

Answer №1

To efficiently process the array, iterate through it just once.

const myObject = {
 item1: {
  visible: true
 },
 item2: {
  visible: true
 },
 item3: {
  visible: false
 }
};


var objs = [ 
    { name: 'item1', visible: false },
    { name: 'item2', visible: false },
    { name: 'item3', visible: false }
];

objs.forEach(obj => {
  const property = myObject[obj.name];
  if (property) {
    obj.visible = property.visible;
  }
});


console.log(objs);

Answer №2

Iterate through each element in myObject, and locate the corresponding object in objs using the find method, then update the value of that specific object:

for (let o in myObject) {
  let obj = objs.find(i => i.name == o)
  if(!obj) continue
  obj.visible = myObject[o].visible
}

Check out this functional demonstration:

const myObject = {
 item1: {
  visible: true
 },
 item2: {
  visible: true
 },
 item3: {
  visible: false
 }
}

var objs = [ 
    { name: 'item1', visible: false },
    { name: 'item2', visible: false },
    { name: 'item3', visible: false }
]

for (let o in myObject) {
  let obj = objs.find(i => i.name == o)
  if(!obj) continue
  obj.visible = myObject[o].visible
}

console.log(objs)

Answer №3

const objectData = {
 item1: {
  active: true
 },
 item2: {
  active: true
 },
 item3: {
  active: false
 }
};


var items = [ 
    { name: 'item1', active: false },
    { name: 'item2', active: false },
    { name: 'item3', active: false }
];

Object.getOwnPropertyNames(objectData).forEach(property => {
  let item = items.find(i => i.name === property);
  if (item) {
    item.active = objectData[property].active;
  }
});

console.log(items);

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

As I spun four images along the outer edge of a circular border, one image came to a halt at 90 degrees, revealing its content. Now, I am looking to enlarge that particular

I managed to rotate four images around a circular border and stop one image at every 45-degree angle. However, I am struggling to enlarge the image that stops at 90 degrees on the website while still showing the content of the respective image when it reac ...

Is there a method to prevent data loss on page refresh by persisting data stored in a database?

I'm currently developing a commenting feature for a blog using the latest version of NextJs. The text input collects data and sends it to the 'Vercel' hosted database. I am able to successfully fetch the data from the frontend as expected. ...

Function cannot be executed through the onchange event handler

I am looking for a solution to track changes in the color of an option element and automatically change the color of the select element when an inactive environment is selected. For example, I want to mark inactive environments with the color #D4D4D4. Is t ...

What steps can be taken to avoid children components from re-rendering every time the parent component's state or props change

I am currently working on a tree component structured like this: <UserOrderApproval> <Table> <TableRow> <ComponentList /> </ChildrenProps1> </Parent> </UserOrderApproval> Currently, I am retrie ...

Combining two functions in JavaScript to target the same div: a simple guide

Currently, the code below is functioning correctly. However, I am interested in combining the checked and click functions into a single function. Is this possible? $(function () { if($("#enablepromo0").is(":checked")) $("#PromoPanel").show(300 ...

jQuery Alert for Double-Checking Email Entry

Is it possible to create a simple alert pop-up using jQuery if the user does not enter the correct email address in the second email input form? Below is my current code: <div id="reservation-request"> <form method="post" action="test.php ...

Is there a way to transfer CSS classes to React children and guarantee they take precedence over the child's own class styles?

I am trying to pass a CSS class from the parent component into the child component. Here is an example: <Parent> <Child /> </Parent> In order to apply a class from the parent to the <Child />, I have done this: <Parent> ...

Steps for preventing a button from being enabled until all mandatory fields are completed

Is it possible to have a button disabled until all required fields are filled out, with the button appearing grey in a disabled state and changing color when all fields are completed? I am facing an issue where clicking on the previous button is causing ...

Transforming various date formats into the en-US format of mm/dd/yyyy hh:mm:ss can be accomplished through JavaScript

When encountering a date format in en-GB or European style (mm.dd.yyyy), it should be converted to the en-US format (mm/dd/yyyy). If the date is not already in en-US format, then it needs to be converted accordingly. ...

hold on for the arrays to be populated with data from the ajax calls

Currently, I am facing an issue on my page where I need to wait for all data to be loaded and stored in the appropriate arrays before proceeding with any actions. The data retrieval involves three separate AJAX calls, but sometimes the loading process take ...

Guide on embedding PHP/MYSQL array into an independent JavaScript document

I'm looking for guidance on how to insert an array from a PHP MySQL page into a separate JavaScript file. Can someone please help me with indicating where to include the PHP URL and provide the correct format for the PHP array code in order to achieve ...

Is there a way to send a boolean to a directive and activate a function when that boolean is altered, all without using $watch?

My goal was to achieve something akin to the following simplified example: class ButtonController { set isFoo(value) { console.log(value); // do something here } } angular.module('myApp', []).directive('mButton', () => ...

A guide to storing a JavaScript variable in a MySQL database using Express.js

Looking for some guidance on node js and expressjs framework. While developing a web application, I've encountered an issue with saving data into the database. Everything seems to be set up correctly, but the data stored in the variable (MyID) is not ...

Difficulty building due to uppercase import in NPM dependency

While working on my Angular project, I encountered a dependency that uses Upper Camel Case import. from "./CSSToMatrix" export { parse, parseMat, toMat, getDistElementMatrix, caculateMatrixDist, getElementMatrix, createMatrix, } from "./C ...

Problem with Safari: File downloaded with name "Unknown" due to Javascript issue

After successfully converting my data to text/csv, I can easily download the file in Chrome. However, when attempting to do so in Safari on an iPad or Mac, it opens a tab with the name "unknown" or "Untitled". The code snippet I am using for this is as fol ...

Analyzing the latest "barchart.com" website

Is there a way to extract data daily from barchart.com, specifically the close/open/high prices? I can't find the values in the page code or the JavaScript script that loads it. Maybe downloading the Excel file using the "download" button is easier, b ...

Iterate through an array, mapping the values and then returning a

Look at the code provided: const { aForm, bForm, eForm, qForm, } = this.form; return ( aForm.isEditing || bForm.isEditing || eForm.isEditing || qForm.isEditing ); Can we optimize this in a different ...

What is the process by which browsers manage AJAX requests when they are made across

I have encountered an issue that is puzzling to me, and I suspect it might be due to my misunderstanding of how the browser handles AJAX requests. Just for context, I am using Codeigniter on an Apache server and triggering AJAX requests with jQuery. The b ...

Analyzing differences between arrays in Perl

I have a specific problem with my code that I'm hoping to get some advice on. I am trying to compare each line of text from one file to the corresponding line in another file, and print out the lines that are different. However, every method I've ...

How can I properly implement a Closure or IIFE to manage an onclick event in ReactJS?

I'm encountering an issue while attempting to utilize the this object in an event handler. An undefined error related to the this object keeps popping up. My development stack includes ReactJS and Redux as well. class Chat extends Component { c ...