简体   繁体   English

如何在嵌套数组中的键值对中输出键

[英]How to output keys in key value pairs in nested arrays JavaScript

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: '' } ] 

您可以通过循环数组来打印对象键,并使用Object.keys()来打印键

Check each item with forEach and if an item's info property is an object, print its keys. 使用forEach检查每个项目,如果项目的info属性是一个对象,则打印其键。

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 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM