两个对象交换键值的数组

时间:2020-01-15 16:39:49

标签: javascript arrays object

我有一个包含两个对象的数组,我希望能够交换两个对象的键值。

    "people":[
        {
            "name":"bob",
            "lastname": "johnson",
            "slot_id": 1
        },
        {
            "name":"terry",
            "lastname": "lucas",
            "slot_id": 2
        },
    ]

我希望能够像这样交换两个slot_id。

    "people":[
        {
            "name":"bob",
            "lastname": "johnson",
            **"slot_id": 2**
        },
        {
            "name":"terry",
            "lastname": "lucas",
            **"slot_id": 1**
        },
    ]

提前谢谢!

2 个答案:

答案 0 :(得分:2)

如果要交换2个值,则需要一个临时变量,这样在分配新值时就不会丢失:

const tmp = people[0].slot_id

people[0].slot_id = people[1].slot_id
people[1].slot_id = tmp

如果您不想使用临时变量,还有另一种可能性:

people[0].slot_id += people[1].slot_id
people[1].slot_id = people[0].slot_id - people[1].slot_id
people[0].slot_id -= people[1].slot_id

您还可以使用数组解构(由@ ASDFGerte提出)

[people[0].slot_id, people[1].slot_id] = [people[1].slot_id, people[0].slot_id]

答案 1 :(得分:1)

const person1Id = people[0].slot_id

people[0].slot_id = people[1].slot_id
people[1].slot_id = person1Id