简体   繁体   English

如何遍历所有对象数组?

[英]How to loop through all the array of objects?

I have an Array of Object to be used to draw a HTML Table: 我有一个对象数组可用于绘制HTML表格:

Array(5)
0: Object
   id: 4
   name: Sand Jane
   address: Green Sand Street
   ...
   ...
   ...
1: Object
2: Object
...
...
...

I am able to do a single name column defined search with 我可以用一个name列定义搜索

const temp = this.temp.filter(function (d) {
            return d.name.toLowerCase().indexOf(val) !== -1 || !val;
        });

temp will contain the filtered data of this.temp temp将包含this.temp的过滤数据

Now I just can't figure out how to loop through all object keys (id,name,address...) so that I can do a global column search in the Table. 现在,我只是想不通如何遍历所有对象键(id,name,address ...),以便可以在表中进行全局列搜索。

UPDATE : I have tried this, 更新 :我已经尝试过了,

const temp = [];
        this.temp.forEach(element => {
            for (let key in element) {
                if (element.hasOwnProperty(key)) {
                    let v = element[key];
                    if (v.toString().toLowerCase().indexOf(val) !== -1 || !val) {
                        temp.push(element);
                    }
                }
            }
        });

It works but with performance issues. 它有效,但存在性能问题。

RESOLVED: Putting a break after temp.push fixed this issue. 已解决:在temp.push之后temp.push break temp.push解决此问题。 Thank you all for the guidelines and references. 谢谢大家的指导和参考。

temp.forEach(item=>{
    for(let key in item) {
       //item[key] gives you access to each value
    }
})

You can iterate through for loops or even you can usefor loop inside a for loop. 您可以遍历for循环,甚至可以在for循环内使用for循环。 Either way it's self explanatory. 无论哪种方式,这都是不言自明的。

var dictionary = {
"employee1":[
    {"id":"0","name":"Google"},
    {"id":"1","name":"eBay"}
],
"employee2": [
    {"id":"2","name":"Yahoo"},
    {"id":"3","name":"Facebook"}
]
};
var employee1 = dictionary.employee1;
var employee2 = dictionary.employee2;

for ( var i in employee1) {
    var id = employee1[i].id;
    var name = employee1[i].name;
    console.log(id);
    console.log(name);
}

for ( var i in employee2) {
    var id = employee2[i].id;
    var name = employee2[i].name;
    console.log(id);
    console.log(name);
}

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

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