-2

I am trying to map key dynamically while constructing the object it is not creating ID as key.

main.js

const data = [
 {
  "ID":"Bellaire",
  "Name":"Bellaire", 
  "Address": "1st Ave"
 },
 {
  "ID":"Bellaire",
  "Name":"Bellaire",
  "Address": "1st Ave"
 },
 {
  "ID":"Champions Forest",
  "Name":"Champions Forest",
   "Address": "2nd Ave"
 }
 ]
function test(data,id){
 const filterData = data.filter(e => {
   if(e.ID === id) {
     return true;
   }
 });
const finalResponse = {
  filterData[0].ID: ["other Details"]
}
 return finalResponse;
}
console.log(test(data,"Bellaire"));

expected output

[ { "Bellaire": ["other Details"] } ]
hussain
  • 6,587
  • 18
  • 79
  • 152
  • Does this answer your question? [How to group an array of objects by key](https://stackoverflow.com/questions/40774697/how-to-group-an-array-of-objects-by-key) – AZ_ Apr 25 '20 at 05:17

1 Answers1

1

Since filterData[0].ID returns a string and in order to set it as a key, you will just need to wrap it like [filterData[0].ID]:

const finalResponse = {
   [filterData[0].ID] : ["other Details"]
}

Demo:

const data = [{ID:"Bellaire",Name:"Bellaire",Address:"1st Ave"},{ID:"Bellaire",Name:"Bellaire",Address:"1st Ave"},{ID:"Champions Forest",Name:"Champions Forest",Address:"2nd Ave"}];

function test(data, id) {
  const filterData = data.filter(e => {
    return e.ID === id
  });
  const finalResponse = {
    [filterData[0].ID] : ["other Details"]
  }
  return finalResponse;
}
console.log(test(data, "Bellaire"));
palaѕн
  • 72,112
  • 17
  • 116
  • 136