0

Here is a simple printing out of the values of an array:

export default function App() {
  var data = [{name:'Jhon', age:28, city:'HO'},
            {name:'Onhj', age:82, city:'HN'},
            {name:'Nohj', age:41, city:'IT'}
           ];

    data.map(({name, age}, i) => {
       console.log(name + ' ' + age);
    })
 }

Now, I receive the names of the values in another array, how can I print out the values of the array using a variable:

    export default function App() {
      var data = [{name:'Jhon', age:28, city:'HO'},
                {name:'Onhj', age:82, city:'HN'},
                {name:'Nohj', age:41, city:'IT'}
               ];
     //Here are the keys of the array
     var colNames =  ['name','age'];
    
        data.map(({colNames}, i) => {
        //So I can do something like
           console.log(colNames[0] + ' ' + colNames[1]);
        })
}

Thanks!

2 Answers 2

1

As per your code, you are trying to destructure colNames property from the data object which is not present on the data object.

You can use below snippets to print the values from the data object.

export default function App() {
    var data = [{name:'Jhon', age:28, city:'HO'},
           {name:'Onhj', age:82, city:'HN'},
           {name:'Nohj', age:41, city:'IT'}
           ];
    //Here are the keys of the array
    var colNames =  ['name','age'];

    data.map((item, i) => {
        //So I can do something like
        console.log(item[colNames[0]] + ' ' + item[colNames[1]]);
    })
}
Sign up to request clarification or add additional context in comments.

Comments

0

I get the sense that you want:

export default function App() {
  var data = [{name:'Jhon', age:28, city:'HO'},
            {name:'Onhj', age:82, city:'HN'},
            {name:'Nohj', age:41, city:'IT'}
           ];
  
    // assuming you got the colNames from somewhere..
    data.map(item => {
       const text = colNames.map(c => item[c]).join(' ');
       console.log(text);
    });
}

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.