如何在 JavaScript 中将对象的键添加到数组中

huangapple go评论101阅读模式
英文:

How to add the key of the object to the array in js

问题

我不知道如何不重写数组'aiStaff'。请帮助我。

英文:

I have such objects:

  1. robot {
  2. id
  3. skill
  4. currentWorkPlace
  5. }
  6. warehouse {
  7. aiStaff
  8. currentStatus
  9. boxes
  10. }

I have to write a function that should add the id of a new worker to the aiStaff array, and write a reference to the warehouse object to the job in the currentWorkPlace. But I don't know how not to change the array in the warehouse.('registerRobot' function should not rewrite array 'aiStaff' inside 'warehouse' object) and I don't have to create a new variable

There is my code:

  1. function registerRobot(robot, warehouse) {
  2. robot.currentWorkPlace = warehouse;
  3. robot.currentWorkPlace.aiStaff = [robot.id];
  4. }

I dont know how to not rewrite array 'aiStaff'. Please help me Guys.

答案1

得分: 0

看起来你的 warehouse.aiStaff 是一个数组。在这种情况下,修改你的函数将机器人 ID 添加到数组中:

  1. function registerRobot(robot, warehouse) {
  2. robot.currentWorkPlace = warehouse;
  3. robot.currentWorkPlace.aiStaff.push(robot.id);
  4. }
英文:

It looks like your warehouse.aiStaff is an array. In this case change your function to add the robot ID to the array:

  1. function registerRobot(robot, warehouse) {
  2. robot.currentWorkPlace = warehouse;
  3. robot.currentWorkPlace.aiStaff.push(robot.id);
  4. }

答案2

得分: 0

如果我理解正确,您需要“添加”一个新的机器人,但您遇到了整个数组被覆盖的问题。

考虑到warehouse.aiStaff是一个数组,如果您想要添加一个新的“worker”,您需要将新项目使用push方法添加到数组中。

  1. function registerRobot(robot, warehouse) {
  2. robot.currentWorkPlace = warehouse;
  3. robot.currentWorkPlace.aiStaff.push({
  4. id: robot.id
  5. });
  6. }
英文:

If I understood correctly you need to 'add' a new robot, but you are having the issue that the entire array gets overridden.

Considering warehouse.aiStaff is an array, if you want to add a new 'worker' you need to push the new item into the array.

  1. function registerRobot(robot, warehouse) {
  2. robot.currentWorkPlace = warehouse;
  3. robot.currentWorkPlace.aiStaff.push({
  4. id: robot.id
  5. });
  6. }

huangapple
  • 本文由 发表于 2023年2月14日 00:13:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438461.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定