Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

548
Views
About Set() and for..in... in javascript
function menuSet(menuArray) {
  let flatmenus = menuArray.flat();//Method gom cac Array con va Array cha thanh 1 Array duy nhat
  let combinedMenu = new Set();//Tao Object trong do Loai bo cac phan tu con trung nhau
  flatmenus.forEach(dish => { //Dua cac phan tu trong Flatmenus vao Object Set() moi duoc tao
    combinedMenu.add(dish)
  });
  const menuCombined = document.querySelector('#combined-menu')
  for (let dish of combinedMenu) {
    let foodNode = document.createElement('li')
    foodNode.innerText = dish;
    menuCombined.appendChild(foodNode);
  }
}
menuSet([["Tacos", "Burgers"], ["Pizza"], ["Burgers", "Fries"]])

Why for..in loop can not deal with the object but it comes Ok with Set()? Doesn't Set() return an Object?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Why for..in loop can not deal with the object but it comes Ok with Set()? Doesn't Set() return an Object?

I think you meant for...of loop (that's what your code uses), not for...in.

To use for...of on something, it has to be iterable (it has to implement the standard way of getting an iterator from it). Objects are not iterable by default. Array, Set, Map, and String objects are iterable, and you can make your own iterable objects, but plain objects aren't iterable.

I assume you're using Set to remove duplicates ("Burgers" appears twice in flatmenus). You don't need that forEach call to put the values in the Set, you can pass flatmenus into new Set directly:

for (let dish of new Set(flatmenus)) {
    // ...
}

That works because the Set constructor accepts an iterable object and adds all of the values from its iterator to the Set. Arrays are iterable.

about 4 years ago · Juan Pablo Isaza Report

0

You can do something like this:

const menuSet=(menuArray)=> {
  let flatmenus = new Set(menuArray.flat());
  const menuCombined = document.querySelector('#combined-menu')
  flatmenus.forEach((dish)=>{
    let foodNode = document.createElement('li');
    foodNode.textContent = dish;
    menuCombined.appendChild(foodNode);
  });
}
menuSet([["Tacos", "Burgers"], ["Pizza"], ["Burgers", "Fries"]])
<html><head><body><div id="combined-menu"></div></body></head></html>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!