Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map array of objects

Please read carefully the question, this is not a duplicate of:

  • ECMAScript 6 arrow function that returns an object
  • javascript cannot map array of objects with nested values
  • map function for objects (instead of arrays)
  • Loop through an array in JavaScript
  • map function for objects (instead of arrays)
  • Loop through an array in JavaScript

Let's consider the following array of object:

var obj = [{ 'key1' : 'value1' }, { 'key2' : 'value2' }];

I would like to map the array to get keys and values for each object. Something like:

obj.map((key, val) => console.log(key, val));

I already try many stuff like Object.entries(obj) but it always results in complicated solution with many brackets like Object.entries(obj)[0][1]

Is there a simple, nice and efficient way to map an array of object? Note I need key and value for each object

like image 615
Fifi Avatar asked Apr 20 '26 14:04

Fifi


2 Answers

You seem like you only want to print it out or access them:

.map changes an array to a different array, which doesn't seem like what you are looking for.

var objs = [{ 'key1' : 'value1' }, { 'key2' : 'value2' }];

objs.forEach(obj => { 
  for (let p in obj) console.log(p, obj[p]); 
});

If you are looking for key1=value1&key2=value2 as the answer and you know you only have 1 key and value in each object, then it is:

let objs = [{ 'key1' : 'value1' }, { 'key2' : 'value2' }];

let s = objs.map(obj => `${Object.keys(obj)[0]}=${Object.values(obj)[0]}`).join("&");

console.log(s);

But you probably want to use encodeURIComponent() to encode the params, making it:

let objs = [{ 'key1' : 'value1 hello' }, { 'key2' : 'value2 & 3' }];

let s = objs.map(obj => `${encodeURIComponent(Object.keys(obj)[0])}=${(encodeURIComponent(Object.values(obj)[0]))}`).join("&");

console.log(s);

If your keys are all alphanumeric and underscore characters, then you shouldn't need to use encodeURIComponent() on the key.

like image 161
nonopolarity Avatar answered Apr 23 '26 03:04

nonopolarity


var obj = [{ 'key1' : 'value1' }, { 'key2' : 'value2' }];
obj.forEach(el => {
  for (var prop in el) {
    console.log(prop, el[prop])
  }
})

// results: 
// key1 value1
// key2 value2
like image 23
jacopotaba Avatar answered Apr 23 '26 05:04

jacopotaba