Dilhan Bhagat
Dilhan Bhagat

Reputation: 488

How can I add a unique ID to each object in an array?

I have this array of objects and I am trying to add a unique id to each object to have the desired output as shown below .But since I am new to Javascript this is a bit hard for me please can someone help me .

This is my Array Object Input:

const list =  [

     {"value": "Tape Measure"},
     
     {"value": "Lawn Mower"}
  ],

]

This is my desired output with unique id's:

const desiredOuput = [
  {
    "id": "ur95tnnt949003",
    "value": "Tape Measure",
  },
  {
    "id": "0698080805kg",
    "value": "Lawn Mower",
  },

]

Upvotes: 2

Views: 7381

Answers (5)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Here is sample method to generate randId. In the method, 1) considering mix of numbers (0-9) and lower case alphabets (a-z). 2) required length of randId (size param)

const randId = (size) => {
  const nums = Array.from({ length: 10 }, (_, i) =>
    String.fromCharCode("0".charCodeAt(0) + i)
  );
  const alphabets = Array.from({ length: 26 }, (_, i) =>
    String.fromCharCode("a".charCodeAt(0) + i)
  );
  const chars = [...nums, ...alphabets];
  const rand = (length) => Math.floor(Math.random() * length);
  return Array.from({ length: size }, () => chars[rand(chars.length)]).join("");
};

const list = [{ value: "Tape Measure" }, { value: "Lawn Mower" }];

const newlist = list.map(({ value }) => ({ value, id: randId(6) }));

console.log(newlist);

Upvotes: 1

Stefan Dobre
Stefan Dobre

Reputation: 138

npm install uuid

then:

const { v4: uuidv4 } = require('uuid');

list.forEach(el=> el.id = uuidv4());

Upvotes: 0

Anurag Kumar
Anurag Kumar

Reputation: 129

  • This function will give you fully unique id
function genID() {
    const timeStamp = Date.now();
    let str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    let Id = '';
    for (let i = 0; i < 7; i++) {
        let rom = Math.floor(1 +(str.length -1)*Math.random());
        Id += str.charAt(rom);
    }
    Id += timeStamp.toString();
    return Id;
}
  • You can also use only timeStamp
let id = Date.now();

Upvotes: 0

shweta ramani
shweta ramani

Reputation: 400

Try this...

const list = [{
  "data": [{
      "value": "Tape Measure"
    },

    {
      "value": "Lawn Mower"
    }
  ],
  "name": "Garden Todo",
}]

const result = list.map(l => {
  l.data = l.data.map(d => ({id:Math.floor(Math.random() * Date.now()), ...d}));
  return l;
})
console.log(result);

Upvotes: 0

Adam Azad
Adam Azad

Reputation: 11297

const list = [{
  "data": [{
      "value": "Tape Measure"
    },

    {
      "value": "Lawn Mower"
    }
  ],
  "name": "Garden Todo",
}]


const res = list.map(o => {
  o.data = o.data.map(d => ({ ...d,
    id: randomId()
  }));

  return o;
})

console.log(res)

// Change this as desired
function randomId() {
  return Math.random()
}

Upvotes: 2

Related Questions