Search code examples
javascripttypescriptlodash

Array of objects iteration to get key and value


I have an array of objects. I want to efficiently extract keys and its value out of it.

Example:

let data = [{'Car':'Honda'}, {'car':'Volvo'}];

I want car as key and its values separately. How I can achieve it in efficient manner (even using lodash)?

Expected output will be:

key : Car  value : Honda
key : car  value : Volvo

Solution

  • You can iterate over the array and access the key and the value of properties for each object in question.

    let data = [{
      'Car': 'Honda',
      'hello': 'hi'
    }, {
      'car': 'Volvo'
    }];
    
    data.forEach((obj) => {
    	Object.keys(obj).forEach((key) => {
      		console.log("key : " + key + " - value : " + obj[key]);
      });
    });

    lodash snippet

    let data = [{
      'Car': 'Honda',
      'hello': 'hi'
    }, {
      'car': 'Volvo'
    }];
    
    _.forEach(data, (obj) => {
    	_.forEach(Object.keys(obj), (key) => {
      		console.log("key : " + key + " - value : " + obj[key]);
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.core.min.js"></script>