I have an object with key value pairs inside an array:

error : [ { firstName : true },
          { lastName : false },
          { email : true }
        ]

I want to fetch the key from objects.

I tried this, but this will show undefined in output

let result = error.map((row, index) => { 
          console.log("key" + row[0] + " index " + index);
}

enter image description here

2 Answers

1
Jack Bashford On

Use Object.keys:

 

const obj = {
error : [ { firstName : true },
      { lastName : false },
      { email : true }
    ]
}

const keys = obj.error.flatMap(Object.keys);

console.log(keys);

You may need this for an older browser:

 

const obj = {
error : [ { firstName : true },
      { lastName : false },
      { email : true }
    ]
}

const keys = obj.error.map(Object.keys).reduce((acc, curr) => acc.concat(curr));

console.log(keys);

0
Ankit Agarwal On

Use map() with Object.keys():

var data = {
  error: [{
      firstName: true
    },
    {
      lastName: false
    },
    {
      email: true
    }
  ]
};
var keys = data.error.map(e => Object.keys(e)[0]);;
console.log(keys);

Or use forEach() with spread syntax:

var data = {
  error: [{
      firstName: true,
      address: false
    },
    {
      lastName: false
    },
    {
      email: true
    }
  ]
};
var keys = [];
data.error.forEach(e => keys = [...keys, ...Object.keys(e)]);;
console.log(keys);