Home > Back-end >  How to add ids to every element of an array in JavaScript?
How to add ids to every element of an array in JavaScript?

Time:03-03

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:

[
  {
    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.

CodePudding user response:

Maybe the confusing part whas that there is an object inside an array:

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

res = Object.entries(arr[0]).map( ([ids,data],index) => ({
  id: index,
  ids,
  data
  })  )
  
console.log(res)

CodePudding user response:

How about using for...in on the object. I'm not sure if you'll ever have more than 1 object in your starting array but if you pull the object out, you can iterate over the key values.

const startingData = [
  {
    "1": "data1",
    "5": "data2",
    "6": "data3"
  }
];

const objectToLoop = startingData[0];
const endingData = [];
let i = 0;
for(const entry in objectToLoop){
  
  let itemToAdd = {
    id: i,
    ids: entry,
    data: objectToLoop[entry] 
  };

endingData.push(itemToAdd);
i  ;
}

console.log(endingData);

CodePudding user response:

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);

CodePudding user response:

const sample = {
  "1": "data1",
  "5": "data2",
  "6": "data3"
};

function init(input) {
  let result = [];

  const keys = Object.keys(input);

  for (let i = 0; i < keys.length; i  = 1) {
    const label = keys[i];
    const value = input[label];

    result = [
      ...result,
      {
        id: `${i}`,
        ids: `${label}`,
        data: `${value}`,
      }
    ];
  }

  return result;
}

console.log(init(sample));

CodePudding user response:

const test = [
  {
    "1": "data1",
    "5": "data2",
    "6": "data3"
  }
];

let result = [];
Object.entries(test[0]).forEach(([key, value], index) => {
  result.push({
      id: index,
      ids:key,
      data: value
  });
});
console.log(result);
  • Related