Assigning identical values to all properties of an object

Let's consider an object structured like this:

myObject = {
    "a_0" : [{"isGood": true, "parameters": [{...}]}],
    "a_1" : [{"isGood": false, "parameters": [{...}]}],
    "a_2" : [{"isGood": false, "parameters": [{...}]}],
    ...
};

The goal is to change all the isGood values to true. One attempt involved using _forOwn method to iterate over the object and forEach to loop through each property, but it wasn't successful.

_forOwn(this.editAlertsByType, (key, value) => {
    value.forEach(element => {
        element.isSelected = false;
    });
});

However, an error occurred with the message:

value.forEach is not a function

Answer №1

you almost had it! Utilize the Object.keys() method to extract the keys from your anObject object, then iterate through them to update each array.

anObject = {
  "a_0": [{
    "isGood": true,
    "parameters": [{}]
  }],
  "a_1": [{
    "isGood": false,
    "parameters": [{}],
  }],
  "a_2": [{
    "isGood": false,
    "parameters": [{}],
  }],
  //...
};

Object.keys(anObject).forEach(k => {
  anObject[k] = anObject[k].map(item => {
    item.isGood = true;
    return item;
  });
})
console.log(anObject);

Answer №2

Implementing forEach() and map() functions on the object named anObject

const anObject = {
    "a_0" : [{"isGood": true, "parameters": []}],
    "a_1" : [{"isGood": false, "parameters": []}],
    "a_2" : [{"isGood": false, "parameters": []}]
};

Object.keys(anObject).forEach((key) => {
    anObject[key].map(obj => obj.isGood = true);
});

console.log(anObject);

Answer №3

Give this a shot:

for (let property in myObject) {
  myObject[property]["isPositive"] = true;
}

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

Tips on utilizing setInterval in a Vue component

When defining the timer in each individual my-progress, I use it to update the value of view. However, the console shows that the value of the constant changes while the value of the view remains unchanged. How can I modify the timer to successfully change ...

Django plugin designed for showing a real-time feed of messages - powered by Dajax or Jquery?

Currently, I am attempting to set up a section in my Django application where updates or messages from the server can be displayed once specific tasks are done. I had initially looked into using a plugin that utilizes Dajax / Jquery for this feature, but ...

Angular 4: Utilizing reactive forms for dynamic addition and removal of elements in a string array

I am looking for a way to modify a reactive form so that it can add and delete fields to a string array dynamically. Currently, I am using a FormArray but it adds the new items as objects rather than just simple strings in the array. Here is an example of ...

Reorganizing array of objects in JavaScript

Currently, I am tackling a challenge within a ReactJS application. My task involves extracting JSON data related to various products and restructuring this information for the purpose of categorization and displaying it accordingly. Despite my attempts wi ...

Aurelia validator fails to refresh user interface

Despite the aurelia-validator plugin working correctly for form submission and validation, with all properties updating properly, the UI does not reflect any changes. There is no red outline around incorrect properties or error messages displayed. I have r ...

I am encountering an issue where I am unable to successfully fetch a cookie from the Express backend to the React

const express = require("express"); // const storiesRouter = require("./routes/storiesRouter") // const postsRouter = require("./routes/postsRouter"); // const usersRouter = require("./routes/usersRouter"); const cors = require("cors"); const cookieParser ...

Goodbye.js reliance on lodash

In my search for the most lightweight and speedy jQuery implementation for server-side NodeJs, I've come across Cheerio as the best option. However, I've noticed that Cheerio has a code-size of around 2.6 MB, with approximately 1.4 MB attributed ...

Error: Routing parameters are missing in the Ui-sref link

Below is the state definition: .state('root.countryreport', { url: '/report/:country', params: { data: null }, views: { 'container@': { templateUrl: ...

Do arrays permanently retain the strings stored within them?

As an 11-year-old who has been learning Javascript for the past month and a half, I am currently working on creating a login/register system. Right now, my focus is on the register part. I have a question: when adding a string/number/boolean to an array, d ...

Issue with getStaticProps in Next.js component not functioning as expected

I have a component that I imported and used on a page, but I'm encountering the error - TypeError: Cannot read property 'labels' of undefined. The issue seems to be with how I pass the data and options to ChartCard because they are underline ...

Problem with Ionic Material's item class

Currently, I am working on the Ionic material demo app and encountering an issue. When I do not use the "item class," everything works fine, but the UI does not appear as expected because that class is missing. The code is as follows: <div class ...

What is the best way to store HTML in a variable as a string?

Imagine if I have a variable: let display_text = "Cats are pawsome!" I aim to show it as such: <div> <b>Cats</b> are pawsome! </div> To be clear, dynamically enclose the word "cats" whenever it shows up. ...

"Learn the art of refreshing data in AngularJS following the use of $emit event handling

I am in need of assistance with AngularJS. How can I re-initialize a variable in scope after using emit? Here is an example code snippet: $scope.uiConfig = {title: "example"}; $scope.$emit('myCustomCalendar', 'Data to send'); $scop ...

JavaScript can be used to create a fullscreen experience without any toolbars, scrollbars, and the like, without having

Is there a way for me to expand the current window I am using to fullscreen mode and eliminate all toolbars? ...

Error: No package.json file found after publishing npm package with ENOLOCAL

Ecosystem using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="335d435e73051d021d03">[email protected]</a> using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a8a9a2a386b0fee8f7f7e ...

Encountering a circular structure while attempting to convert to JSON -- starting at an object created by the 'HTMLInputElement' constructor

I have been trying multiple solutions to fix this issue, but I'm still struggling to resolve it. My application is built using Next.js and I am using axios as the HTTP client. import React, {useState} from 'react' import axios from 'axi ...

Creating a personalized ESLint rule specifically for Redux reducers

Currently working with Redux and Redux Toolkit alongside ESLint presents a challenge. Sometimes, when adding my extraReducers, I find that I do not need both the state and action properties provided by Redux. As a result, ESLint throws an error in these c ...

How can we configure AngularJS UI-Bootstrap to set a minimum date of 90 days ago and a maximum date of today?

I am currently working on an AngularJS and UI-Bootstrap app that includes a datePicker with certain date restrictions. As someone new to Angular, I am seeking advice on how to set the minDate to 90 days ago and the maxDate to today's date. Check out ...

Best practices for effectively managing errors within JSON web tokens

I am a novice attempting to manage JWT verification. Within the function below, my goal is for the system to generate a new access token based on the refresh token if the user's access token has expired. import { asyncHandler } from "../utils/asy ...

What should I do when using _.extend() in express - override or add in fields?

When an object is extended by another object with values set for some of the extended fields, will it be rewritten or will the new values be added? For example: const PATCH_REQUEST_SCHEMA = { 'type': 'object', 'title' ...