函数变量作为对象字段选择器

时间:2018-09-01 19:48:40

标签: javascript

我具有以下功能:

populateClinicRoomSelect(object) {
    var selectArray = [];
    var options = [];
    for(var key in object) {
        if(object.hasOwnProperty(key)) {
            options = {
                value: object[key].id,
                label: object[key].RoomName,
            };
            selectArray = selectArray.concat(options);
        }
    }
    return selectArray;
}

这个想法是从对象数组中获取两个已定义的字段,并将其放置在新数组中。工作正常。除了“ id”字段和“ RoomName”字段是不同的字段名称外,我还有其他一些功能完全相同。有什么方法可以将“ id”和“ RoomName”作为函数变量来在函数中定义它们?

2 个答案:

答案 0 :(得分:0)

当然,您可以像使用[arg]一样将字段名称作为参数传递并使用[key]访问器:

function populateClinicRoomSelect(object, valueField, labelField) {
  var selectArray = [];
  var options = [];
  for(var key in object) {
    if(object.hasOwnProperty(key)) {
      options = {
        value: object[key][valueField],
        label: object[key][labelField],
      };
      selectArray = selectArray.concat(options);
    }
  }
  return selectArray;
}

const object = {
  a: {
    id: 1,
    room: 'first room'
  },
  b: {
    id: 2,
    room: 'second room'
  }
}

const result = populateClinicRoomSelect(object, 'id', 'room');

console.log(result)

答案 1 :(得分:-1)

您的意思是这样吗?

function populateClinicRoomSelect(object, value, label) {
    value = value || "id"; // defaults value to id
    label = label || "RoomName"; // defaults label to RoomName
    var selectArray = [];
    var options = [];
    for(var key in object) {
        if(object.hasOwnProperty(key)) {
            options = {
                value: object[key][value],
                label: object[key][label],
            };
            selectArray = selectArray.concat(options);
        }
    }
    return selectArray;
}

let obj = { 1: { id:1, RoomName: "Blue Lounge" }, 2: { id:2, RoomName: "Red Lounge" } }

console.log(populateClinicRoomSelect(obj, 'id', 'RoomName'));