How to use a string as an object with diferent parameters in javascript?

Manuel

New Member
#1
I have an array of post that is call test and the next code takes other array and push the post if the name equals something:
Mã:
var test = [];
docs = [{name: 'mateo',lastName: 'mateo'},
        {name: 'Jhon',lastName: 'smith'}}]

docs.forEach(function(item) {
    if(item.name === 'mateo'){
        test.push(item);
    }
});
I want to use different parameters for the name, but I don´t know how, I was trying to use something like this but it did´t work:
Mã:
var test = [];
docs = [{name: 'mateo', lastName: 'mateo'},
        {name: 'Jhon',lastName: 'smith'}}]
const varNames = ['name','lastName'];

docs.forEach(function(item) {
    for(i = 0; i < varNames.length; i++){
        if(item.[varNames[i]] === 'mateo'){
            test.push(item);
            console.log(varNames[i]);
        }
     }
});
 

Admin

Administrator
Thành viên BQT
#2
That's not how bracket notation work. Change

Mã:
if(item.["varNames[i]"] === 'mateo') {
To:
Mã:
if(item[varNames[i]] === 'mateo') {
By the way, you should break the loop once an item is matched:
Mã:
if(item[varNames[i]] === 'mateo') {
    test.push(item);
    break;
}
You could also replace that whole for loop with another array function called some, so that your whole code looks like:
Mã:
docs.forEach(function(item) {
    var check = varNames.some(function(varName) {
        return item[varName] === 'mateo';
    });
    if(check) {
        test.push(item);
    }
})
Which can be shorter if you use an arrow function:
Mã:
docs.forEach(item => {
    if(varNames.some(varName => item[varName] === 'mateo')) {
        test.push(item);
    }
})
 
Top