-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?

1
  • 3
    Can you please show us your attempt on solving this? Commented Apr 24, 2019 at 9:26

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

3 Comments

i'm getting 0:  ["firstname", "karan"]1: ["lastname", "khimani"] in different keys
@KaranKhimani Try pressing Run code snippet above, it works perfectly. I also believe what you're describing is a browser's console's way of showing the contents of an array.
exaclty let me try
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

2 Comments

Getting console error Uncaught SyntaxError: Identifier 'userDetails' has already been declared @Grégory NEUT
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.