0

I have these values:

var firstHeader = $('#header0').text(); // 6KP
var secondHeader = $('#header1').text(); // 7KP
var thirdHeader = $('#header2').text(); // 8KP

var first = $('#input0').val(); // 77
var second = $('#input1').val(); //88
var third = $('#input2').val(); // 99

And I need to create a JSON object to have this:

{6KP:77, 7KP:88, 8KP:99}

I tried to do this but without success:

var data = { firstHeader: first, secondHeader: second, thirdHeader: third };

data = JSON.stringify(data, null, ' ');

And my response is this:

{firstHeader: 77, secondHeader:88, thirdHeader:99}

How can I put the values instead of these var names?

1
  • I know there are multiple dupes of this, btw, so searching first is probably the best choice. Commented Jul 6, 2018 at 14:27

3 Answers 3

5

You use array notation, e.g.,

var data = {}; 
data[firstHeader] = first;

If you're using ES6 you can use the shorthand:

var data = { 
  [firstHeader]: first, 
  // Etc.
};
Sign up to request clarification or add additional context in comments.

1 Comment

@AnkitAgarwal It will if you're using ES6, e.g., transpiling or in an environment where it's supported. I made no mention of it working natively--I said "using ES6" on purpose.
2

You need to use square brackets to evaluate the variable value as a key name:

var data = {};
data[firstHeader] = first;
data[secondHeader] = second;
data[thirdHeader] = third;

WORKING EXAMPLE

var firstHeader = '6KP';
var secondHeader = '7KP';
var thirdHeader = '8KP';

var first = '77';
var second = '88';
var third = '99';
var data = {};
data[firstHeader] = first;
data[secondHeader] = second;
data[thirdHeader] = third;
console.log(JSON.stringify(data));

Comments

1

Replace below line

var data = { firstHeader: first, secondHeader: second, thirdHeader: third };

with

var data ={};

data[firstHeader]= first;
data[secondHeader]= second;
data[thirdHeader]: third ;

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.