如何将新属性添加到现有的javascript对象

时间:2019-08-07 21:48:27

标签: arrays reactjs loops javascript-objects

我尝试将新属性“ id”添加到对象数组。我一开始不喜欢这个原因是因为首先我必须以随机顺序对数组进行排序。我尝试使用forEach循环执行此操作,但是它不起作用。为什么?

response.css('[bo-text="offre.intitule"]::text').extract()

在控制台中,我得到了以下数组。如果我拒绝,则ID号会更改,但仍然没有排序。

    CreateCardList = () => {
        const { cardsAmount } = this.state;
        let halfList = [];
        let card = {};
        for (let i = 0; i < cardsAmount/2; i++) { // choose cards for half of the amount
            card = {
                type: 'hero',
                isHidden: true
            }
            halfList.push(card);
        }
        let entireCardList = [...halfList, ...halfList]; // duplicate the array
        entireCardList.sort((a, b) => 0.5 - Math.random()); // sorting the array in random order
        for (let j = 0; j < entireCardList.length; j++) {
            entireCardList[j].id = j;
        }
        console.log(entireCardList);
    }

3 个答案:

答案 0 :(得分:1)

制作卡片entireCardList时不会复制对象,因此最终得到[object1, object2, ... , object1, object2, ...]阵列。因此,当您分配id时,它将覆盖值。要解决此问题,您可以为数组的后半部分创建对象的副本:

let entireCardList = [...halfList, ...halfList.map(x => ({...x}))]

对于我来说,以随机顺序对包含完全相同元素的数组进行排序没有任何意义

答案 1 :(得分:1)

您的问题来自以下行:let entireCardList = [...halfList, ...halfList];
您正在通过考虑复制halfList来尝试创建一个全新的数组,但是正在发生什么;散布运算符不会创建数组的深层副本,因此它只是浅层副本。并且,当您将id分配给列表中的一项时,实际上它们被分配给多个项,因为它们具有相同的引用。

一个解决方案将以下内容:let entireCardList = [...halfList, ...halfList];替换为:

const firstHalf = JSON.parse(JSON.stringify(halfList));
const secondHalf = JSON.parse(JSON.stringify(halfList));
let entireCardList = [...firstHalf, ...secondHalf];

它应该可以按预期的方式工作:)

工作示例:

const cardsAmount = 6
const halfList = [];

for (let i = 0; i < cardsAmount / 2; i++) {
  halfList.push({ type: 'hero', isHidden: true });
}

const firstHalf = JSON.parse(JSON.stringify(halfList));
const secondHalf = JSON.parse(JSON.stringify(halfList));
const entireCardList = [...firstHalf, ...secondHalf];

// If cards are the same, then there is no point in sorting...
entireCardList.sort((a, b) => 0.5 - Math.random());

for (let j = 0; j < entireCardList.length; j++) {
  entireCardList[j].id = j;
}

console.log(entireCardList);

答案 2 :(得分:0)

因为您创建了一个包含对对象的引用对的数组,所以这是为什么:)

let entireCardList = [...halfList, ...halfList];