访问对象中的键和标签并在另一个数组上循环,并在循环的数组元素内分配键和标签:JavaScript

时间:2019-08-13 10:31:17

标签: javascript arrays object

我有一个名为roomDetails的对象,我需要从中添加标签。获得标签后,我需要遍历patientArray并将标签分配为roomLabel的值。

roomDetails = {

room01{label: "Room 1"},
room02{label: "Room 2"},
room03{label: "Room 3"},
room04{label: "Room 4"}
}


let patientArray = [

{ roomLabel: '', name: 'John'},
{ roomLabel: '', name: 'Shawn'},
{ roomLabel: '', name: 'Gereth'},
{ roomLabel: '', name: 'Elminster'}
]

所以PatientArray应该是

let patientaArray = [

{ roomLabel: 'Room 1', name: 'John'},
{ roomLabel: 'Room 2', name: 'Shawn'},
{ roomLabel: 'Room 3', name: 'Gereth'},
{ roomLabel: 'Room 4', name: 'Elminster'}
]

我尝试过

   Object.keys(roomDetails).map((key, index) => {

            const roomLabel = roomDetails[key].label;
            console.log(roomLabel); // this outputs correctly as `Room 1`, `Room 2`.....

            patientArray.forEach((pi, index) => {


                pi.roomLabel = roomDetails[key].label; // output is always `Room 4`, the pi.roomLabel is being overwritten on each iteration. 

            });
        });

请帮助我指导正确的解决方案,并以我的理解。谢谢。

1 个答案:

答案 0 :(得分:0)

roomDetails不是代码中的对象。

以下代码段不是一个很好的代码段,因为它不能针对 roomDetails 对象和 PatientArray 的不同长度进行“防御”。我认为您必须考虑一种更谨慎的算法来处理所有可能的情况。

而且:您不应该变异 PatientArray -修改输入数据不是一个好主意。最好创建一个副本( map()返回具有修改后值的新数组; PatientArray 保留其开头。

const roomDetails = {
  room01: {
    label: "Room 1"
  },
  room02: {
    label: "Room 2"
  },
  room03: {
    label: "Room 3"
  },
  room04: {
    label: "Room 4"
  }
}

const patientArray = [{
    roomLabel: '',
    name: 'John'
  },
  {
    roomLabel: '',
    name: 'Shawn'
  },
  {
    roomLabel: '',
    name: 'Gereth'
  },
  {
    roomLabel: '',
    name: 'Elminster'
  }
]

const finalArray = Object.values(roomDetails).map((e, i) => {
  return {
    roomLabel: e.label,
    name: patientArray[i].name
  }
})

console.log(finalArray)