Home > Software engineering >  Getting output 4 undefined in javascript
Getting output 4 undefined in javascript

Time:03-08

This is code to only output the specified columns of the object. However, I am getting the output 4 times undefined.

const array1 = [{
  name: 'k',
  age: 5,
  sex: 'f'
}, {
  name: 'a',
  age: 2,
  sex: 'm'
}];

const result = function(col, arr) {
  for (let obj of col.values()) {
    for (let i = 0; i < arr.length; i  ) {
      console.log(arr[i].obj);
    }
  }
}

result(['name', 'age'], array1);

CodePudding user response:

You need to take the items of cols and change the accessor of arr.

const
    array1 = [{ name: 'k', age: 5, sex: 'f' }, { name: 'a', age: 2, sex: 'm' }],
    result = function(col, arr) {
        for (const key of col) {
            for (let i = 0; i < arr.length; i  ) {
                console.log(arr[i][key]);
            }
        }
    };

result(['name', 'age'], array1);

  • Related