Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code.

const devices = searchResult.results.forEach(device => {
    const temp = Object.keys(device.fields);

    for(var property in temp) {
        if(device.fields.hasOwnProperty(property)) {
            if (!usedPropertiesAcrossModels.has(property)) {
                delete device.fields[property];
            }
        }
    }
}

Attempting to remove keys from a JavaScript object that are not part of a specific set. Despite debugging and confirming only one element in the set and 15 elements in device.fields, nothing is actually being deleted from device.fields. It's perplexing! Additionally, temp appears to be undefined until outside of the loop. The variable property remains undefined despite there being items in temp. Quite baffling!

Answer №1

searchResult = {};
searchResult.results = [{
    fields:{
     name: 'hello',
     type:'gekko',
     random:'randomString'
      }
   }
]
usedPropertiesAcrossModels = {
  name: 'hello',
  random:'hello'
}
   

const devices = searchResult.results.forEach(device => {
                const
                temp = Object.keys(device.fields).map((property)=>{
                if(device.fields.hasOwnProperty(property)) {
                        if (!usedPropertiesAcrossModels.hasOwnProperty(property)) {
                            delete device.fields[property];
                        }
                    }
                }) 
                    
                    
   })
   console.log(searchResult)

Resolved the issue by using map instead of for in loop to get keys of the object, or using for of as suggested by Martin.

Answer №2

Using <code>const temp = Object.keys(o)
will provide you with an array of the object's keys. Instead of using a for in loop, it is recommended to use a for of loop as you need to iterate through the values, not just the keys in the temp object:

const o = { x: 10, y: 20, z: 30 };
const temp = Object.keys(o);
console.log(temp);

// This will loop through the keys in `temp`, so 0, 1, 2
for (const key in temp) {
  console.log('incorrect:', key); 
}

// This will loop through the values in `temp`, so 'x', 'y', 'z'
for (const key of temp) {
  console.log('correct:', key);
}

// Alternatively, you can also iterate using `forEach()`
temp.forEach(key => {
  console.log('correct:', key);
});

When using the for of loop, there is no need for the hasOwnProperty check.

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

Remove a div element with Javascript when a button is clicked

I am working on a project where I need to dynamically add and remove divs from a webpage. These divs contain inner divs, and while the functionality to add new divs is working fine for me, I'm facing some issues with removing them. The code snippet b ...

Tips for sending a JSON object from a PHP file to a JavaScript variable

Forgive me if this has already been discussed in a previous post, I have not been able to find the answer. My PHP page generates an array in JSON format: [{ "chemical":"Corrosion_Inhibitor", "TargetDose":81, "AppliedDose":26, "ppbbl":"$0.97" ...

Utilizing a function from a library in an Object within a Typescript environment

Currently, I am working on assigning a field within my interface to a function from an external library in the following manner: import { Accelerometer, } from 'expo-sensors'; type SensorInterface = { permChecker: () => Promise<Permiss ...

Issue with Angular Swiper carousel: Error message pointing to node_modules/swiper/angular/angular/src/swiper-events.d.ts

I am attempting to implement a carousel in Angular using Swiper (). An error message is appearing: Error: node_modules/swiper/angular/angular/src/swiper-events.d.ts:3:50 - error TS2344: Type 'SwiperEvents[Property]' does not meet the constraint ...

Initiate the execution of JavaScript functions in the loaded partial view using Ajax

I am currently working with a javaScript function that loads a partial view within my page's layout using the following logic: $('.follow-tasks').click(function (e) { e.preventDefault(); var $followtaskList = $("#td-" + $(this).attr ...

What is the best way to dynamically update the selected option in a dropdown menu within a Rails application using a variable?

Working on a project that involves a select drop-down menu containing a list of currencies. Want to enhance user experience by automatically selecting the default value in the dropdown based on the user's country (will be utilizing the geoip gem). To ...

Obtaining a pdf file using javascript ajax is a straightforward process

Looking to access my JavaScript file generated by a microservice (byte[]): public int retrieveLabel(Request request, Response response) throws IOException { response.header("Access-Control-Allow-Origin", "*"); ArrayList<JSONObject> orders = ...

Enhancing User Experience with Load Indicator during State Changes in React Native

I'm facing an issue where the page for displaying a single item is loading slowly - I need to delay the page from loading until the object has changed. After checking the navigation params through console log, I can see that the id changes when each b ...

The presence of multiple renderings occurring due to Google Maps InfoBox and an AJAX call

I'm encountering a problem with my implementation of the InfoBox and I'm looking for insights on potential solutions. Currently, I have around 1000 client-side markers that are dynamically added to the page. They are created using the following ...

Set up npm and package at the main directory of a web application

Currently, I am in the process of developing a web application using node.js. Within my project structure, I have segregated the front-end code into a 'client' folder and all back-end logic into a 'server' folder. My question revolves a ...

How about: "Using Node.js and Express to declaratively define a route for

I am facing an issue managing my routes in declarative objects and initializing/registering the endpoint handlers using one or more of these objects. The problem arises when I attempt to register the handlers in a loop of the declarative routes, methods, ...

Enhance the appearance of rows in a table by adding a captivating marquee effect to those with

I'm working with a table that has 7 rows and 2 tabs for Sunday and Monday. The row corresponding to the current time is highlighted in red. I wanted to know if it's possible to add the following <marquee>My first Row</marquee> effe ...

What is the most efficient way to query through a Firestore database containing 5,000 users?

We are currently facing a challenge with our staffing application, which is built using vuejs and a firestore database containing over 5,000 users. Our primary issue lies in the need for a more efficient layout that allows admins to search for users within ...

Internet Explorer 10 not triggering the 'input' event when selecting an option from the datalist

Within this particular scenario, there is an input field paired with a corresponding datalist element. My aim is to develop JavaScript code that actively listens for when a user chooses an item from the list. Most resources suggest utilizing the "input" ev ...

The Next.js React framework seems to be having trouble reading user input from a

I'm encountering an issue when attempting to save form email/password registration using Next.js as it is throwing an error. import {useState} from 'react' type Props = { label: string placeholder?: string onChange: () => void na ...

Dynamically determine the data type of a value by analyzing the key property within a function

I have created a custom hook that extends the functionality of the useStata function by accepting key and value props; import { Dispatch, SetStateAction, useCallback, useState } from 'react'; export type HandleModelChangeFn<T> = (key: keyo ...

Exclude certain packages from being processed in webpack

After setting up my webpack configuration, everything was running smoothly with the specified packages in the package.json: { "peerDependencies": { "react": "16.13.1", "react-dom": "16.13.1", ...

Utilizing MUI for layering components vertically: A step-by-step guide

I am looking for a way to style a div differently on Desktop and Mobile devices: ------------------------------------------------------------------ | (icon) | (content) |(button here)| ----------------------------------------- ...

Establishing the data type for the state coming from the API

Whenever I try to add a new API response to the status, it shows as undefined. I need to filter out the incoming data from randomcocktail and then put it to use. Random.tsx import { useState, useEffect } from "react"; import { CocktailType } ...

Encountering an unexpected token ';' in a random generator while attempting to utilize an if-else statement for determining DOM manipulation

After dabbling in programming on and off for a few years, I've finally decided to dive deep with some simple personal projects. One of the tasks I'm working on is creating a randomizer for a pen and paper RPG, where it samples from an array at ra ...