-6

if we create one object like

const userDetails={firstname:'karan',lastname:'khimani'}

then expected output like

[["firstname", "karan"], ["lastname", "khimani"]]

How did i convert this?

2 Answers2

2

Use Object.entries:

const userDetails = { firstname: "karan", lastname: "khimani" };
const arr = Object.entries(userDetails);
console.log(arr);

I believe this is an ES7 feature - so if you need to support older browsers, use map with Object.keys:

var userDetails = { firstname: "karan", lastname: "khimani" };
var arr = Object.keys(userDetails).map(function(key) {
  return [key, userDetails[key]]
});
console.log(arr);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

So what you want to do is create an array, which contains keys and values as arrays.

You should have a look at Object.keys and Object.entries.

Soluce are below, but try to find it yourself first looking at the documentation of the functions I've given you.


const userDetails = {
  firstname: 'karan',
  lastname: 'khimani'
};

const transformed = Object.keys(userDetails).map(x => [x, userDetails[x]]);

console.log(transformed);

Why not always use Object.entries? Because It's not well supported on every browser.

const userDetails = {
  firstname: 'karan',
  lastname: 'khimani'
};

const transformed = Object.entries(userDetails);

console.log(transformed);

enter image description here

Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
  • Getting console error `Uncaught SyntaxError: Identifier 'userDetails' has already been declared` @Grégory NEUT – Karan Khimani Apr 24 '19 at 09:36
  • I think that you copy pasted my code and appended it to your existing code. If you do so, the variable `userDetails` will be declared two times and that's why you have the error. Removes either your declaration or mine. You should follow a javascript tutorial – Orelsanpls Apr 24 '19 at 09:37