-1

I have a function that returns the following:

{ 'random_string': '' }

Where random_string is an id that I do not know until it is returned. How do I extract the value of random_string in JS? Thank you.

Contradictions
  • 137
  • 3
  • 15

2 Answers2

2
var a = { 'random_string': '' }
console.log(Object.keys(a)[0])
munleashed
  • 1,677
  • 1
  • 3
  • 9
1

Your variable a has a value of type Object. Take a look at the Object prototype's documentation and see which methods are available to you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

You're trying to get your object's first key, and so conveniently you can use Object.keys as follows:

var a = { 'random_string': '' }

// Get array of Object's key values as strings
var aKeys = Object.keys(a);
console.log(aKeys);

// Print first key, in this case you only have one
console.log(aKeys[0]);

But based on your comments, you're going about this wrong.

If your "random_string" property identifier is truly random, you'd want to store the random string as an object property value.

That might look something like this:

// Generate some random string value
var random = Math.random().toString(36).substring(7);

// Create an object with a predefined object property identifier
var data = { 'random_value': random };

// Access the random value using your known property identifier
console.log(data.random_value);
Trent
  • 4,208
  • 5
  • 24
  • 46