Is it possible to use Symbol.iterator in an Object via prototype in JavaScript?

What is the reason behind the inability to add Symbol.iterator to an Object in this way?

Object.prototype[Symbol.iterator];

    let obj = {num: 1 , type : ' :) '}
    for (let p of obj) {
      console.log(p);
    }
    // TypeError: obj is not iterable
    

Answer №1

In order to enable iteration over an object, you must set a generator function to

Object.prototype[Symbol.iterator]
.

Object.prototype[Symbol.iterator] = function*() {
  for (let key in this) {
    yield this[key];
  }
};

let exampleObj = {
  number: 10,
  message: 'Hello!'
}
for (let prop of exampleObj) {
  console.log(prop);
}

Answer №2

Not assigning anything to

Object.prototype[Symbol.iterator]
means that the iterator function is not defined. If you were to assign a proper iterator function, the code might work as intended.

Object.prototype[Symbol.iterator] = function*(){
  for(let entry of Object.entries(this))
     yield entry
};

let obj = {num: 1 , type : ' :) '}
for (let [k,v] of obj) {
  console.log(k,v);
}

// another way
console.log(...obj)

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

The command `grunt.option('force', true) isn't functioning properly

After reviewing the grunt.options documentation, my initial expectation was that I could initiate a Grunt task programmatically with the force option activated in this manner: var grunt = require('grunt'); grunt.option('force', true); ...

Getting the Featured Image from a Post Link in Wordpress: A Step-by-Step Guide

For my Wordpress project, I have a group of links leading to inner pages, each with their own featured image. These links are created using the menu feature in Wordpress. My goal is to allow users to click on these links and have the featured image from t ...

What is the best way to verify changing input fields in vue.js?

Validation of input fields using vuelidate is essential. The input field in question is dynamic, as the value is populated dynamically with jsonData through the use of v-model. The objective: Upon blur, the goal is to display an error if there is one; ho ...

Saving URI from HTTP request in Javascript using Google Drive API: A step-by-step guide

I'm struggling to understand and implement the instructions provided at https://developers.google.com/drive/v3/web/manage-uploads#save-session-uri While I've successfully used javascript to upload files to Google Drive, I am now faced with a cha ...

Changing the structure of a webpage in real-time and inserting new elements into the document

I have a custom x-template filled with a survey element (including a text field and radio button). Upon loading the screen, the database sends a JSON object to the UI based on previously stored sections. This JSON object is then used to populate the survey ...

What is causing the scripts to fail when I attempt to press a button?

Clicking on the button is supposed to slowly reveal phone numbers on the page. Here are the HTML Codes: <span id="show-phone-numbers" class="btn btn-success"> <i class="fe fe-phone-call"></i> Show Phone Nu ...

Leveraging HTML5's local storage functionality to save and manage a collection of list elements within `<ul>`

I need help with saving a to-do list in HTML so that it persists even after refreshing the browser. Can anyone assist me? html <!DOCTYPE html> <html> <head> <title>My To-Do List</title> <link rel="sty ...

remove MongoDB entry using unique identifier

I am currently working on a blog project using nodejs, express, and mongodb. My goal is to delete a specific document by its ID. For instance, if I want to remove a blog post with the ID 52976b1b0855c7e81a6192e9, I would make a request to localhost:3000/bl ...

Issue with material-ui-dropzone, the DropzoneAreaBase component not displaying the preview of the uploaded files

Has anyone encountered issues with the DropzoneAreaBase component from the material-ui-dropzone library? I am having trouble getting it to display added file previews. Any insights into why this might be happening? <DropzoneAreaBase onAdd={(fileObjs) ...

Incorporating the dot notation, unleash the potential of AngularJS interpolation binding, expressed as `

I want to incorporate the AngularJS interpolation binding with dot notation. <div ng-repeat="item in items"> <input type="checkbox" ng-model="form.city.{{item.region}}.enabled"> </div> However, I keep encountering errors with the ng-m ...

I am experiencing issues with the ng-dropdown-multiselect library and it is not functioning

Check out this awesome library for creating dropdown menus using angularjs and twitter-bootstrap-3 at: . I am trying to implement the examples provided. In my html, I have: <div ng-dropdown-multiselect="" options="stringData" selected-model="stringMod ...

Connect to dynamically generated div on separate page

I am facing an issue with my navigation bar drop down menu that displays event titles fetched from the database. I want users to be able to click on a specific event and have the page scroll to the dynamically generated content for that event. However, it ...

The operation in Mongo DB carried out a $pull to eliminate the ObjectId("... id") from the nested sub-array

I've scoured every nook and cranny of the internet in an attempt to resolve this issue, but so far I've come up empty-handed. My goal is to use the mongodb $pull function to remove an Object from an array nested inside a Schema. I've success ...

PhantomJS Karma encountering SyntaxError when trying to export variables

I've encountered an issue while running Karma and PhantomJS. When I attempt to run, the console displays the following message: 22 03 2016 14:58:47.865:WARN [karma]: No captured browser, open http://localhost:9876/ 22 03 2016 14:58:47.875:INFO [karm ...

Facing an ESIDIR error in NextJs, despite the fact that the code was sourced from the official documentation

For an upcoming interview, I decided to dive into learning Next.js by following the tutorial provided on Next.js official website. Everything was going smoothly until I reached this particular section that focused on implementing getStaticProps. Followin ...

The color of the last clicked DIV is supposed to stay permanent, but for some unknown reason

I'm attempting to replicate this design in my project: http://jsfiddle.net/AYRh6/26/ However, I am facing issues with it and cannot pinpoint the exact problem in the code. I am using code for a toggle effect. Any assistance would be greatly appreciat ...

Adding optional properties to TypeScript interfaces

As discussed in this post, the optional ? operator is commonly used to indicate that a function parameter can be omitted. But what is the significance of the ? operator when it appears on interface parameters? For instance, consider the following TypeScrip ...

Is it possible to simultaneously use two $scoped variables within an Angular controller?

Currently, I am developing an angular application that connects to a Rails backend and interacts with the database through API calls to receive JSON objects. My challenge lies in defining multiple scoped variables within a controller. At the moment, I have ...

Unable to process jquery AJAX request

Hello, I've been attempting to make a simple ajax call to a method in my code behind. Despite keeping it straightforward for testing purposes, I keep encountering errors. It seems like a basic mistake, but I'm at a loss on how to proceed. The pro ...

Display the div element only when it is positioned in the center of the page

I am looking to create a smooth fade-in effect for a div when the user scrolls away from the top of the page, but I want the div to be hidden again as they approach the bottom of the page. Specifically, I would like the div to remain hidden when it is wit ...