0

I have multiples entities and they have the same structure ("entityId" and "name"), like this:

Gender

"gender" : {
     genderId: 1,
     name: "someValue"
}

EducationLevel

"educationLevel" : {
     educationLevelId: 1,
     name: "someValue"
}

ProfessionalTitle

"professionalTitle" : {
     professionalTitleId: 1,
     name: "someValue"
}

I wrote this function to get a generic JSON but of course is wrong. How can I set "field+Id" correctly?

My function

function getGenericJson(field, nameValue, idValue){ 
var idName = field + "Id"; 
var fieldJson = { 
name: nameValue, 
field+"Id": idValue 
}
return fieldJson; 

}

Input example

getGenericJson("gender", "someValue", 1);
Daniela Morais
  • 2,125
  • 7
  • 28
  • 49
  • are you trying to return a json string object? – funcoding Apr 25 '17 at 19:29
  • @funcoding There is no such thing as "JSON Object" or "JSON String Object". It's either JSON (a String), or an Object. "JSON" stands for "JavaScript Object Notation" – blex Apr 25 '17 at 19:30
  • I think you're wrong! https://www.w3schools.com/js/js_json_objects.asp – funcoding Apr 25 '17 at 19:33
  • and from another website: JSON objects can be created with JavaScript. Let us see the various ways of creating JSON objects using JavaScript −https://www.tutorialspoint.com/json/json_objects.htm – funcoding Apr 25 '17 at 19:34
  • Well, maybe I'm wrong, but I think both of these websites are using the wrong terminology. Saying _JavaScript Object Notation Object_ sounds wrong to me, like saying "ATM machine", which would mean _Automated Teller Machine machine_. [Read this if you want](http://stackoverflow.com/questions/6489783/whats-the-difference-between-javascript-object-and-json-object). Anyway, as long as we understand each other... – blex Apr 25 '17 at 19:40

3 Answers3

2

In ES6, you can write it like this:

function getGenericJson(field, nameValue, idValue){
  return { 
    name: nameValue, 
    [field+"Id"]: idValue 
  }
}

In ES5, you would write it like this:

function getGenericJson(field, nameValue, idValue){
  var fieldJson = { 
    name: nameValue
  };

  fieldJson[field + "Id"] = idValue;
  return fieldJson;
} 
samanime
  • 25,408
  • 15
  • 90
  • 139
0

Try wrapping it with brackets as follows:

var fieldJson = {
    ...,
    [ field + "Id" ]: idValue
}
Kyle Richardson
  • 5,567
  • 3
  • 17
  • 40
0

DEMO

ES5 :

function getGenericJson(field, nameValue, idValue) { 
    var fieldJson = {}; 
    fieldJson.name = nameValue;
    fieldJson[field+"Id"] = idValue;
    return fieldJson;
};

console.log(getGenericJson("gender", "someValue", 1));

ES6 using backticks(template literals) :

function getGenericJson(field, nameValue, idValue) { 
    let fieldJson = {};
    let fieldName = `${field}ID`;
    fieldJson.name = nameValue;
    fieldJson[fieldName] = idValue;
    return fieldJson;
};

console.log(getGenericJson("gender", "someValue", 1));
Debug Diva
  • 26,058
  • 13
  • 70
  • 123