简体   繁体   中英

How to loop through all the array of objects?

I have an Array of Object to be used to draw a HTML Table:

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

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

temp will contain the filtered data of 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.

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. 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. 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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