JavaScript Course

Objects – iterate through objects (key / value)

Let’s begin with simple object.

var object2convert = {
  key1: 'value 1',
  key2: 'value 2',
  key3: 'value 3'
}

What we want to do firstly is to iterate through object by each key.

Iterate Object by key (EcmaScript 5)

We will use for … in loop like in below example:

for (var key in object2convert) {
        if (object.hasOwnProperty(key)) {
           user[key] = object[key];
        }
}

Let’s create a function to make it reusable:

function object2array(object) {
  var array = [];
  
  for (var key in object) {
    if (object.hasOwnProperty(key)) {
      var newObj = {
        key: key,
        value: object[key]
      }
      
      array.push(newObj)
    }
  }
  
  return array;
}

So to make a test how it works:

var object2convert = {
  key1: 'value 1',
  key2: 'value 2',
  key3: 'value 3'
}

function object2array(object) {
  var array = [];
  
  for (var key in object) {
    if (object.hasOwnProperty(key)) {
      var newObj = {
        key: key,
        value: object[key]
      }
      
      array.push(newObj)
    }
  }
  
  return array;
}

console.log(object2array(object2convert));

This will return:

[
  {
    key: 'key1',
    value: 'value 1'
  },
  {
    key: 'key2',
    value: 'value 2'
  },
  {
    key: 'key3',
    value: 'value 3'
  }
]

Iterate Object by key (EcmaScript 6)

Let’s now try to make it EcmaScript 6 compatible:

const convert = (object) => Object
                              .keys(object)
                              .map(id => ({
                                key: id,
                                value: object[id]
                              }))

Now lets test it finally:

const convert = (object) => Object
                              .keys(object)
                              .map(id => ({
                                key: id,
                                value: object[id]
                              }));

var object2convert = {
  key1: 'value 1',
  key2: 'value 2',
  key3: 'value 3'
}

console.log(convert(object2convert));
Please follow and like us:
error

Leave a comment

Your email address will not be published. Required fields are marked *