-1

I am trying to add a value in place of json object key but it always returns variable name. My Code:

var projectName='';
let tempArray=[];
let output={};        
for(i=0;i<myJsonArray.length;i++){
        name = myJsonArray[i].Project;
        tempArray.push(myJsonArray[i]);
    }
    output= {projectName :tempArray};
    console.log(JSON.stringify(output));

This returns a JSON as

{"projectName":[{"Day":"MON","Project":"ABC","Billing Rate":"xxx"},{"Day":"TUE","Project":"ABC","Billing Rate":"xyx"}]}

But I need something like this:

{"ABC":[{"Day":"MON","Project":"ABC","Billing Rate":"xxx"},{"Day":"TUE","Project":"ABC","Billing Rate":"xyx"}]}

Can someone help on what I am missing here.

Kind Regards.

Ramaraju.d
  • 1,301
  • 6
  • 26
  • 46

1 Answers1

1

You should wrap the project name into [] that would help to make a value become a key

var name = '';
let tempArray = [];
let output = {};
for (i = 0; i < myJsonArray.length; i++) {
  name = myJsonArray[i].Project;
  tempArray.push(myJsonArray[i]);
}
output = {
  [name]: tempArray
};
console.log(JSON.stringify(output));

P/s: I don't see any projectName variable there, so I replace it by name instead.

Nick Vu
  • 14,512
  • 4
  • 21
  • 31