Fifi
Fifi

Reputation: 3605

Map array of objects

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

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

Upvotes: 2

Views: 6751

Answers (3)

ROOT
ROOT

Reputation: 11622

Not as clean as what @nopole answer, but this kind achieve what you want for a key, value object.

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

objs.forEach(obj => { 
  // loop over keys-and-values
  for (let [key, value] of Object.entries(obj)) {
    console.log(key, value);
  }
});

Also this works for object with more than one key:

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

objs.forEach(obj => { 
  // loop over keys-and-values
  for (let [key, value] of Object.entries(obj)) {
    console.log(key, value);
  }
});

Upvotes: 1

nonopolarity
nonopolarity

Reputation: 151216

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.

Upvotes: 4

jacopotaba
jacopotaba

Reputation: 94

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

// results: 
// key1 value1
// key2 value2

Upvotes: 1

Related Questions