Exploring the for... in loop for iteration in JavaScript

I am facing an issue with populating an empty array named objToArray using a for-in-loop. The goal is to fill the array with numbers from a hash object checkObj, but only if the keys have values that are greater than or equal to 2.

const checkObj = {
  oddNum: 1,
  evenNum: 2,
  foundNum: 5,
  randomNum: 18
};

const objToArray = [];

for (let values in checkObj) {
  if (Object.values(checkObj) >= 2 ) {
    objToArray.push(checkObj.values())
    }
}

console.log(objToArray);

Despite expecting three elements, [2, 5, 18], my current output is an empty array when logging objToArray.

Answer №1

Consider using

Object.values(checkObj).filter(x => x >= 2);
.

  1. Retrieve an array of all values using Object.values(checkObj).
  2. Filter the array to get values greater than or equal to 2 with .filter(x => x >= 2).

If you prefer to utilize a for ... in loop, it loops through the object keys allowing access to values through obj[key]. In your case, by declaring for (let values in checkObj), the variable values holds the key to each value in checkObj. Therefore, you can retrieve the value using checkObj[values].

See the output below.

const checkObj = {
  oddNum: 1,
  evenNum: 2,
  foundNum: 5,
  randomNum: 18
};

// Approach 1
let result = Object.values(checkObj).filter(x => x >= 2);
console.log(result);

// Approach 2
const objToArray = [];
for (let values in checkObj) {
  if (checkObj[values] >= 2) {
    objToArray.push(checkObj[values]);
  }
}
console.log(objToArray);

Answer №2

Is this what you were looking for?

The for...in loop goes through all the keys of an object, not the values.

const checkObjects = {
  evenNumber: 2,
  oddNumber: 3,
  primeNumber: 7,
  randomNum: 20
};

const objectsToArray = [];

for (let keyValue in checkObjects) {
  if (checkObjects[keyValue] >= 3) {
    objectsToArray.push(checkObjects[keyValue])
  }
}

console.log(objectsToArray)

Answer №3

Give this a try:

const sampleObject = {
    firstNumber: 3,
    secondNumber: 6,
    thirdNumber: 9,
    fourthNumber: 12
};
    
const objectValuesArray = [];

for (let [key, value] of Object.entries(sampleObject)) {
    if(value>=6){
        objectValuesArray.push(value);
    }
}

console.log(objectValuesArray);

Answer №4

Give this a shot

const testObject = {
  first: "apple",
  second: "banana",
  third: "carrot",
  fourth: "date"
};

let objectArray = [];
objectArray = Object.values(testObject).filter(item => item.length > 5);
console.log(objectArray);

Answer №5

Give this a shot: Hopefully you understood it ..

const testObject = {
  firstNum: 3,
  secondNum: 6,
  thirdNum: 9,
  fourthNum: 12
};

let objectArray = [];

for (let val of Object.values(testObject)) {
  console.log(val);
  if (val >= 6) {
    objectArray.push(val);
  }
}

Answer №6

let numbers = {
  first: 11,
  second: 22,
  third: 33,
  fourth: 44
};

let numArray = []; 

//converting the for loop to a forEach loop that cycles through the keys
Object.keys(numbers).forEach((key) => {
  if (numbers[key]) {
    numArray.push(numbers[key])
  }
})

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

Ways to retrieve base64 encoded information from an image within an HTML document

On my registration form, users have the option to select an avatar from 2 choices: Select a default avatar Upload their own custom avatar This is how I have implemented it in my HTML page. <img id="preview" src="img/default_1.png"> The chosen av ...

The aspect ratio of Threejs sprites is appearing distorted

I'm facing an issue with rendering two objects in an Orthographic camera using Three.js. The objects are not rendering correctly and I'm unsure of the reason behind it. The expected look of the two images is as follows: https://i.sstatic.net/hQ ...

"Encountered an undefined ViewChild error when using Material Angular MatSidenav

Struggling with Material and angular here! Trying to toggle the Sidenav from a different component using viewchild but running into issues with undefined elements. Here's what I have so far: sidenav.component.html <mat-sidenav-container class="ex ...

How to incorporate an icon into a React Bootstrap Dropdown menu

I'm struggling to figure out how to include an icon in my react dropdown button, similar to the one shown in the following example. https://i.sstatic.net/cn0b0.png The react bootstrap package I am currently using does not seem to offer a straightfor ...

Guide on invoking a node.js function from an express-rendered ejs page

My express server currently has a button that triggers a POST request to activate a function in my node.js server. Instead of using a traditional POST request, I am interested in implementing something like AJAX so that the page doesn't reload. Is th ...

How to move a div beneath the JavaScript files in Drupal 7

I am facing a challenge where I need to position a div right above the body tag without interfering with the scripts located above it. Despite my efforts, I have not been successful in achieving this goal. I attempted to use Hook_page_build to position t ...

Can you show me the steps for downloading the WebPage component?

My goal is to save webpages offline for future use, but when I download them as html many of the included components disappear! I attempted opening them in a WebBrowser and downloading as html with no success. One potential solution is to download the ht ...

Ways to disseminate arguments when dealing with an array of arrays in JavaScript

Struggling to pass an array as arguments into the join method on path in node, but hitting a roadblock: var path = require("path"); var paths = [__dirname]; var userInput = ["app", "js"]; paths.push(userInput); var target = path.join.apply(null, paths); ...

What is the current state of Javascript in versions 3.4 and 3.5 of ANTL

Can someone provide information on the current status of the JavaScript target in ANTLR 3.4 or 3.5? I've searched online for answers but haven't found anything conclusive. While I know it was fixed in v3.3 after being broken in v3.2, there is no ...

Utilize the Split method within a loop in Vue.js

I'm currently faced with a challenge where I need to extract the last 3 letters of each filename stored in an API response. The data is coming from a database and one of the columns contains image file names. Here's a snippet of my code: ax ...

Node.js console and endpoint are returning an object, but the JSON object cannot be fetched

Currently, I am working on a project for an online course where I am utilizing an NLP sentiment analysis API. Although I have made significant progress, I seem to be stuck at the final step. When I send the URL for analysis via the API call, I can see the ...

Determine the total number of arrays present in the JSON data

I'm currently working on a straightforward AngularJS project, and here's the code I have so far: This is my view: <tr ng-repeat="metering in meterings"> <td>1</td> <td>{{metering.d.SerialNumber}}</td> ...

Interactive search tool with multiple fields using HTML and JavaScript

I need help developing a search box for structured data, where I want to implement two types of typeahead searches: one for fields and another for values within those fields. The image below illustrates what I am aiming for. https://i.sstatic.net/MRsJ2.png ...

Utilizing Selenium JavaScript to insert a cookie into a request

Trying to add a cookie to the request in Selenium using JavaScript. I followed the documentation at this link, but my code snippet doesn't seem to pass any cookies to the PHP script below on the server. Here is the client-side JavaScript code: var w ...

The functionality of AngularJS routing is malfunctioning

I'm having trouble with implementing angularJS routing on my page. Initially, it was working fine but now the browser is not returning anything. Here's the code snippet: angular.module('myRoutingApp', ['ngRoute']) .conf ...

Leveraging Vue Data for Storing CSS Properties

I am currently utilizing the Quasar framework in conjunction with Vue for my application development. Below is a snippet of my code: <q-tooltip content-class="bg-amber text-black shadow-4" :offset="[10, 10]"> Save </q-tooltip> <q-tooltip c ...

Achieving CSS transition effects using the .appendChild function in JavaScript

When using the mouseenter event, I have a JavaScript function applied to an svg path element: const fadeIn = (event, locale) => { event.target.style.fill = 'hwb(' + (120 - score[locale] * 1.2) + ' 0% 0% / 1)' } This function wor ...

Is it possible to apply capitalization or convert the value of props to uppercase in React?

Despite attempting the toUpperCase method, I am unable to capitalize my props value. Here's the code I have: export default function Navbar(props) { return ( <> <div> <nav class="navbar navbar-expand-lg bg-b ...

Clicking the responsive menu does not reveal the hidden overlay div as expected

Struggling with finding the correct function to open the hidden div of my responsive menu on my new website. Check out my code: https://codepen.io/anon/pen/XRJRGE <a class="page-head__menu" id="js-menu" href="#" onClick="open()">Menu< ...

Encountered the error message "Async callback did not complete within the designated 5000 ms timeframe" when manipulating the `test` function with monkey-patching and employing the useFakeTim

This particular setup is quite specific and after scouring the internet, I couldn't find any similar resources. Hence, I decided to post it here in case it proves helpful to someone. While there are numerous inquiries regarding Jest and the error mes ...