简体   繁体   English

如果数组包含重复项,如何为数组中的每个元素赋予唯一的ID?

[英]How to give each element in array an unique id if array consists of duplicats?

I have an JSON file with an array of 8 objects. 我有一个包含8个对象的数组的JSON文件。

I need to turn it into array with 16 objects, where each object repeats twice and give each of these objects an individual id 我需要将其变成具有16个对象的数组,其中每个对象重复两次,并为每个对象赋予一个单独的ID

I managed to duble number of elements like this 我设法使这样的元素数量增加了两倍

let d = data.reduce(function (res, current) {
        return res.concat([current, current]);
    }, []);

Then I tried adding ids like so 然后我尝试像这样添加ids

d.forEach((item, index) => {
        item.id = index;
    })

And I'm not sure why but all duplicates get the same id 我不确定为什么,但是所有重复项都具有相同的id

Structure of JSON object JSON对象的结构

[
  {
    "name": "name",
    "description": "description"
  }
]

Code

export const fetchData = () => dispatch => {

    let d = data.reduce(function (res, current) {
        return res.concat([current, current]);
    }, []);

    d.forEach((item, index) => {
        item.id = index;
    });

    dispatch({
        type: FETCH_DATA,
        payload: d
    });
  };

current is a reference object, you would need Object.assign({}, current) inside your array to make sure you get 2 copies of the original object, like so: current是一个引用对象,您需要在数组内部使用Object.assign({}, current) ,以确保获得原始对象的2个副本,如下所示:

let d = data.reduce(function (res, current) {
    return res.concat([Object.assign({}, current), Object.assign({}, current)]);
}, []);

Or with the spread operator, like so 或与价差操作员一样

let d = data.reduce(function (res, current) {
    return res.concat([{...current}, {...current}]);
}, []);

As other have mentioned, the issue if you are mutating the same object reference instead of creating new ones. 正如其他人提到的那样,如果您要更改相同的对象引用而不是创建新的对象引用,则会出现此问题。

You can also move the ID assignment into reduce as well: 您还可以将ID分配也移动到reduce中:

 const data = [ { "name": "name", "description": "description" }, { "name": "name2", "description": "description2" } ] const d = data.reduce((res, current) => [ ...res, { ...current, id: res.length }, { ...current, id: res.length + 1 }], []); console.log(d); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM