-1
function abc(req, res, next) {
  let imageName = req.body.name;
   const obj = {
    imageName: {
      status: true,
      url: "abc"
    }
 }

In above function I have a varaible declared 'imageName'. I just need to use result that is got at 'imageName' variable at 'obj'. suppose I get 'alpha' from req.body.name then I want to use that in 'obj' like obj = {aplha: {status: true, url: "abc"} }.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Saroj Maharjan
  • 87
  • 1
  • 2
  • 10
  • 1
    You can do `let obj = {}` and `obj[req.body.name] = { status: true, url: "abc" }` – kgangadhar Feb 12 '18 at 17:55
  • Possible duplicate of [Using a variable for a key in a JavaScript object literal](https://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal) –  Feb 12 '18 at 17:57

4 Answers4

1

You can use bracket notation to provide a dynamic key to an object.

let imageName = 'alpha';
const obj = {
  [imageName]: {
    status: true,
    url: "abc"
  }
}
console.log(obj);

Your code will be

function abc(req, res, next) {
  let imageName = req.body.name;
   const obj = {
    [imageName]: {
      status: true,
      url: "abc"
    }
 }
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
1

If I'm reading your question right, you need to use the bracket notation with the object to get a dynamic key value:

function abc(req, res, next) {
    const obj = {};
    obj[req.body.name] = {status: true, url: "abc"};
}

UPDATE

On a side note, you can still reference the value later using the dot notation later on . . . for example, if you want to later check to see if "obj" has an "alpha" value, you can do it with either if (obj.alpha . . . or if {obj[alpha] . . .), but only the bracket notation approach will work when using a dynamic, variable-based key (e.g., if (obj[req.body.name] . . .)).

talemyn
  • 7,822
  • 4
  • 31
  • 52
0

If I understand the question right you want to update the obj object? do like so

obj['newKey'] = { status: true, url: "abc" }
digital-pollution
  • 1,054
  • 7
  • 15
0

While I cannot find the appropriate use case for this, you could always store the value in req.body.name and use that as a key in your obj like so:

function abc(req, res, next) {
   let imageName = req.body.name;
   const obj = {}
   obj[imageName] = {
      status: true,
      url: "abc"
    }
 }
SerShubham
  • 873
  • 4
  • 10