How to output keys in key value pairs in nested arrays JavaScript

Viewed 415

Inside the array of item, there's an array with with the name 'folder'and inside the array there's 'info' How can I be able to print only the keys and not the value from the info array? as in print out 'created' and 'modified" ?

let item = [
  {
    itemName: 'folder',
    info:
    {
      created:'August 13 2013',
      modified: 'December 06 2017'
    }
  },
  {
    itemName: 'new folder',
    info: 'ruby files'
  },
  {
    itemName: 'documents',
    info: ''  
  }
]

4 Answers

You can print the object keys by looping the array and use Object.keys() to print the keys

Check each item with forEach and if an item's info property is an object, print its keys.

item.forEach(data => {
  if(data.info.constructor === Object) {
    console.log(Object.keys(data.info));
  }
})

look at each property and use a recursing function to go deeper :

  let item = [
  {
    itemName: 'folder',
    info:
    {
      created:'August 13 2013',
      modified: 'December 06 2017'
    }
  },
  {
    itemName: 'new folder',
    info: 'ruby files'
  },
  {
    itemName: 'documents',
    info: ''  
  }
];

var console=window.console;

function displayObj(obj) {
    if (obj instanceof Array) {
        for (var i = 0; i < obj.length; i++) {
            console.log('obj['+i+']='+obj[i]);
            displayObj(obj[i]);
        }

    }
    if (obj instanceof Object) {
        for (var p in obj) {
            console.log('obj.'+p+'='+obj[p]);
            displayObj(obj[p]);
        }
    }
}

displayObj(item);

Well, it's not infinitely recursive, but it works (i'll try to ameliorate it)

let items = [
    {
        itemName: 'folder',
        info:
        {
            created:'August 13 2013',
            modified: 'December 06 2017'
        }
    },
    {
        itemName: 'new folder',
        info: 'ruby files'
    },
    {
        itemName: 'documents',
        info: ''    
    }
];

let Keys = [];

items.forEach((el, index) => {
    Object.keys(el).forEach(key => {
        if(!Keys[index])
            Keys[index] = [];
        if(typeof el[key] === 'object'){
            Keys[index].push(Object.keys(el[key]));
        }
        else {
            Keys[index].push(key);
        }
    })
});

JSFiddle

Related