0

I have an array of objects with the following format

var obj = [{
  "a": 1
}, {
  "b": 2
}, {
  "c": 3
}];

Would want to fetch keys and values out of each object separately inside this array of objects into a new array

Something like this: [{"key:"a","val:"1"],{"key":"b","val":"2"},{"key": "c","val":"3"]}

Have tried the following but it is not working :

var obj = [{
  "a": 1
}, {
  "b": 2
}, {
  "c": 3
}];

const result = obj.map(value => Object.keys(value)[0]);
console.log(result);
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
joy08
  • 9,004
  • 8
  • 38
  • 73

3 Answers3

8

With your current function you're returning just the key, not an object with key and value inside. So following your logic, you just need to add a return that returns an object, which inside have the Object.key and Object.value.

See below, is that what you are looking for?

var arrayObj = [
  {
    "a": 1
  }, 
  {
    "b": 2
  }, 
  {
    "c": 3
  }
];

const result = arrayObj.map((obj) => {  
  return {
      key: Object.keys(obj)[0], 
      val: Object.values(obj)[0]
    }
});
console.log(result);

There's also a possibility yo use Object.entries(obj)[0], as you can see in Anjaneyulu Batta answer.

Danny Buonocore
  • 3,731
  • 3
  • 24
  • 46
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
  • Don't know if it's relevant but OP's example has `"val:"1"` - so the number is turned to a string. Just mentioning it - it might have been a typo in the question or otherwise unimportant. – VLAZ Jul 24 '19 at 12:53
  • that's true, I'll wait if he says something, if necessary I'll adjust to return a string – Calvin Nunes Jul 24 '19 at 12:59
4

We have to use Object.keys property to achieve it. Try below code

var obj = [{
  "a": 1,
}, {
  "b": 2
}, {
  "c": 3
}];

const result = obj.map(value => {
  let [key, val] = Object.entries(value)[0];
  return {key, val}
});

console.log(result)
anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62
1

You can use Array.flatMap() with Object.entries() to convert the array of objects to an array of entries. Then map each entry to an object:

const arrayObj = [{ "a": 1 }, { "b": 2 }, { "c": 3 }];

const result = arrayObj
  .flatMap(Object.entries) // convert to an array of entries
  .map(([key, val]) => ({ key, val })); // convert each entry to an object

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209