最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I add a unique ID to each object in an array? - Stack Overflow

programmeradmin2浏览0评论

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",
  },

]

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",
  },

]
Share Improve this question edited Jun 15, 2022 at 13:01 isherwood 61.2k16 gold badges121 silver badges170 bronze badges asked Sep 26, 2020 at 9:30 Dilhan BhagatDilhan Bhagat 4981 gold badge11 silver badges22 bronze badges 2
  • 2 What is the logic behind those IDs? How can they be generated? What code have you tried already? – str Commented Sep 26, 2020 at 9:35
  • @str I just randomly typed them to illustrate the desired output but I used Date.now() and it's not unique so I really need your help to add unique id's – Dilhan Bhagat Commented Sep 26, 2020 at 9:40
Add a ment  | 

5 Answers 5

Reset to default 2

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()
}

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

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

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

npm install uuid

then:

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

list.forEach(el=> el.id = uuidv4());
发布评论

评论列表(0)

  1. 暂无评论