0

I want to push a JSON object to my array; I tried the following code, but right now it is pushing {"fieldDataType": "test"} whereas I want to have: {"S": "test"} ("S" is what fieldDataType has);

var fieldDataType = "S";
p["KeyConditions"][terms[0].attribute]['AttributeValueList'] = [];
p["KeyConditions"][terms[0].attribute]['AttributeValueList'].push(
//{"S": terms[0].value}
  {fieldDataType: terms[0].value}
);
1
  • {fieldDataType: terms[0].value} should be {S: terms[0].value}; if "S" is something that changes, you can't use a literal. just make a blank object and use array syntax to add a property on: ob={}; ob['the key name']=terms[0].value; Commented Aug 12, 2014 at 21:34

2 Answers 2

2

You may need to define an object and set the key using the variable:

var data = {};
data[fieldDataType] = terms[0].value;
p["KeyConditions"][terms[0].attribute]['AttributeValueList'].push(data);
Sign up to request clarification or add additional context in comments.

Comments

0

You can write it as a string and then parse it, as follows:

var pushVal = JSON.parse('{"' + fieldDataType + '":"' + terms[0].value + '"}');

This value can then be pushed to the array:

myArray.push(pushVal);

Inline, it looks like this

myArray.push(JSON.parse('{"' + fieldDataType + '":"' + terms[0].value + '"}'));

Comments

Your Answer

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