Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add ids to every element of an array in JavaScript?

I have an object which has some values like "1", "5", "6" etc and refers to "data1", "data2", "data3" etc as an object.

I am trying to map this object but it is not mapping and looking for id. Here is the object that I am talking about:

[
  {
    "1": "data1",
    "5": "data2",
    "6": "data3"
  }
]

And here is the object that I need:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  {
    id: "0",
    ids: "1",
    data: "data1"
  },
  {
    id: "1",
    ids: "5",
    data: "data2"
  },
  {
    id: "2",
    ids: "6",
    data: "data3"
  },
  }
]

Is there a way to solve this automatically from the response by JavaScript?

I have this response in my React app and specifically using Refine framework(refine.dev) and when I try to map this response, it is looking for reference. I tried every possible answer here: map function for objects (instead of arrays) but has no luck for my case.

>Solution :

let obj = {
  "1": "data1",
  "5": "data2",
  "6": "data3"
};

const keys = Object.keys(obj);
let resultArray = [];

for (let i = 0; i < keys.length; i++) {
  const tempObj = {
    id: i,
    ids: keys[i],
    data: obj[keys[i]]
  };

  resultArray.push(tempObj);
}


console.log(resultArray);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading