0

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

4
  • 1
    If you want to log the entire objects then just log arr[i]. These objects have no property named obj. They have name, age, and sex. Commented Mar 7, 2022 at 21:09
  • 1
    .obj is not a property on the array item? Commented Mar 7, 2022 at 21:10
  • There is no obj property Commented Mar 7, 2022 at 21:10
  • 1
    Ohh I got it. I should use arr[i][obj] instead of arr[i].obj Thank you. Commented Mar 7, 2022 at 21:12

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.