0

I know how to use objects, but I wonder... Is it possible to convert object key like this:

{"fname":"peter", "lastname":"parker"}

Into this?

var fname = "peter";
var lname = "parker";
5
  • Why would you do this? Simply access to the object property? Like this: var fname = yourobject.fname; var lname = yourobject.lastname; Commented Aug 4, 2014 at 7:14
  • 2
    You can create global variables from the above by attaching properties into the window object (if you are on a browser based execution environment). You cannot possibly introduce dynamically named function scoped (local) variables. Commented Aug 4, 2014 at 7:14
  • 1
    While this is possible, I would strongly suggest instead assigning the object to a variable with a short name and then doing o.fname instead of fname. Commented Aug 4, 2014 at 7:14
  • Is this what you want parse JSON in JavaScript Commented Aug 4, 2014 at 7:14
  • The only solution that may come to my mind involve creating a closure with manually written argument names - nothing really usable. It's not that we all never thought about it, mind you. But in the end it's not just worth the effort. Commented Aug 4, 2014 at 7:17

2 Answers 2

5

I know it is old question but a method you could use is:

const obj = {"fname":"peter", "lastname":"parker"};
const { fname, lastname } = obj;
console.log(fname); // prints "peter"
console.log(lastname); // prints "parker"

Maybe it helps to someone.

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

Comments

-1

Try this to fetch the keys of an object:

var keys = Object.keys({
  fname: "peter",
  lastname: "parker"
});

It returns an array with a length of 2, which looks like this:

// keys[0] === "fname";
// keys[1] === "lastname";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.