Итерация по свойствам объекта

это означает, что http server hosting example.com использует порт 9090 для обработки http-запросов, это директива для браузера, которую он подключает к этому серверу на порту 9090 вместо 80, который он обычно делает, если порт не указано

1807
задан lolbas 13 March 2019 в 10:58
поделиться

2 ответа

Типы способа выполнить итерации объекта в javascript

  • для... в [1 119] цикл

  • для... [1 120] цикл

  • forEach () метод

  • карта () метод

let obj = {
  city1: 'BOM',
  city2: 'BLR',
  city3: 'HYD',
  state: {
    city1: 'Sub-city1',
    city2: 'Sub-city2'
  }
}
console.log('----------------using for...in loop------')
for(let entry in obj) 
  console.log(entry +" -> "+ obj[entry])

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        console.log(key + " -> " + obj[key]);
    }
}
console.log('----------------using for...of loop------')
for (const key of Object.keys(obj)) 
    console.log(key +" -> "+ obj[key]);

for (const [key, value] of Object.entries(obj)) 
    console.log(key +" -> "+ value);

console.log('----------------using forEach loop------')
Object.entries(obj).forEach(([key, value]) => console.log(key +" -> "+ value));
    
console.log('----------------using map function------')
Object.entries(obj).map(([k,v])=> console.log(k+' -> '+v))

способ выполнить итерации вложенного объекта

let obj = {
  city1: 'ALD',
  city2: 'BLR',
  city3: 'HYD',
  state: {
    city4: 'Sub-city1',
    city5: 'Sub-city2'
  }
}
function nestedObj(obj) {
    for (let key in obj) {
        // checking if it's nested to iterate again
        if (obj.hasOwnProperty(key) && 
           (typeof obj[key] === "object")) {
            nestedObj(obj[key])
        } else {
            // showing the flat attributes
            console.log(key + " -> " + obj[key]);
        }
    }
}
nestedObj(obj);
8
ответ дан 22 November 2019 в 20:02
поделиться
if(Object.keys(obj).length) {
    Object.keys(obj).forEach(key => {
        console.log("\n" + key + ": " + obj[key]);
    });
}

// *** Explanation line by line ***

// Explaining the bellow line
// It checks if obj has at least one property. Here is how:
// Object.keys(obj) will return an array with all keys in obj
// If there is no keys in obj, it will return empty array = []
// Then it will get it's length, if it has at least one element,
// it's bigger than 0 which evaluates to true and the bellow 
// code will be executed.
// Else means it's length = 0 which evaluates to false
// NOTE: you can use Object.hasOwnProperty() instead of Object.keys(obj).length
if(Object.keys(obj).length) {

    // Explaining the bellow line
    // Just like in the previous line, this returns an array with
    // all keys in obj (because if code execution got here, it means 
    // obj has keys.) 
    // Then just invoke built-in javascript forEach() to loop
    // over each key in returned array and calls a call back function 
    // on each array element (key), using ES6 arrow function (=>)
    // Or you can just use a normal function ((key) { blah blah }).
    Object.keys(obj).forEach(key => {

        // The bellow line prints out all keys with their 
        // respective value in obj.
        // key comes from the returned array in Object.keys(obj)
        // obj[key] returns the value of key in obj
        console.log("\n" + key + ": " + obj[key]);
    });
}
2
ответ дан 22 November 2019 в 20:02
поделиться
Другие вопросы по тегам:

Похожие вопросы: