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";
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
user3204806
  • 322
  • 4
  • 15
  • Why would you do this? Simply access to the object property? Like this: `var fname = yourobject.fname; var lname = yourobject.lastname;` – briosheje Aug 04 '14 at 07: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. – techfoobar Aug 04 '14 at 07: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`. – user2357112 Aug 04 '14 at 07:14
  • Is this what you want [parse JSON in JavaScript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) – Nipuna Aug 04 '14 at 07: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. – MaxArt Aug 04 '14 at 07:17

2 Answers2

3

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.

J.S.R - Silicornio
  • 1,111
  • 13
  • 16
-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";
Malekai
  • 4,765
  • 5
  • 25
  • 60
Super Hornet
  • 2,839
  • 5
  • 27
  • 55