Manuel Esteban
Manuel Esteban

Reputation: 307

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

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:

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:

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

Upvotes: 2

Views: 47

Answers (3)

Darren
Darren

Reputation: 718

The trick is to iterate over both varNames and docs. You're familiar with .forEach, so this example uses it, though this may be a better case for .filter.

const test = [];
const varNames = ['name', 'otherName'];
const docs = [
  { name: 'mateo' },
  { name: 'name' },
  { name: 'otherName' }
];

varNames.forEach(varName => {
  docs.forEach(doc => {
    if (doc.name === varName) test.push(doc);
  });
});
console.log(test);

Upvotes: 0

Mark
Mark

Reputation: 92440

You should really be using filter() for this, everything will be easier:

let docs = [
  {name: 'mateo', lastName: 'johnson'},
  {name: 'Jhon',lastName: 'smith'},
  {name: 'Mark',lastName: 'mateo'}
]

var test = docs.filter(item =>item.name === "mateo") 
console.log(test)

Then to check for an array of names you can simple use some() to see if some of the properties match:

let docs = [
  {name: 'mateo', lastName: 'johnson'},
  {name: 'Jhon',lastName: 'smith'},
  {name: 'Mark',lastName: 'mateo'}
]
const varNames = ['name','lastName'];

var test = docs.filter(item => varNames.some(name => item[name] == 'mateo'))

console.log(test)

Upvotes: 2

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

That's not how bracket notation work. Change

if(item.["varNames[i]"] === 'mateo') {

To:

if(item[varNames[i]] === 'mateo') {

By the way, you should break the loop once an item is matched:

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:

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:

docs.forEach(item => {
    if(varNames.some(varName => item[varName] === 'mateo')) {
        test.push(item);
    }
})

Upvotes: 3

Related Questions