javascript - 将数组中的数据连接到对象以通过中间人转换其值

标签 javascript arrays javascript-objects

使用 queued_Dr 通过使用 all_appointments 更改其值(如 upcoming_appointments.PCD)的最佳方法是什么?

解决这个问题的最佳方法是什么?

var queued_Dr = ["Dr.Salazar","Dr.Connors","Dr.Johnson","Dr.Pearson"]


upcoming_appointments =
[{"DOB":"01-27-2002","name":"Judy, W." ,"PCD":"Dr-S"}
    ,{"DOB":"08-15-1995","name":"John, V." ,"PCD":"Dr-C"}
    ,{"DOB":"07-05-1992","name":"David, C.","PCD":"Dr-S"}
    ,{"DOB":"01-15-2002","name":"Anna, S." ,"PCD":"Dr-J"}
    ,{"DOB":"01-15-2002","name":"Jeff, D." ,"PCD":"Dr-P"}]


all_appointments = 
[["Dr-S","New York","Dr.Salazar"],
 ["Dr-C","Austin","Dr.Connors"],
 ["Dr-J","Austin","Dr.Johnson"],
 ["Dr-S","New York","Dr.Salazar"],
 ["Dr-P","San Juan","Dr.Pearson"],
 ["Dr-J","Austin","Dr.Johnson"]]

输入:

queued_Dr = ["Dr.Salazar","Dr.Connors","Dr.Johnson","Dr.Pearson"]

期望的输出:

queued_Dr = ["Dr-S","Dr-C","Dr-J","Dr-P"]

实际输出:

[ undefined, undefined, undefined, undefined ]

尝试

const mapTo = (arrayWithNames) => {
  var newArray = []; 
  return arrayWithNames.map(name => {
    const appointment = Object.values(all_appointments)
      .find(appointment => appointment[2] === name);
      newArray.push(appointment[0]);
  })
  return newArray;
}
const result = mapTo(queued_Dr)
console.log(result);

最佳答案

第一种方案是在all_appointments中查找name,返回对应的缩写。

第二种解决方案是只组成缩写而不用其他数组。

const queued_Dr = ["Dr.Salazar","Dr.Connors","Dr.Johnson","Dr.Pearson"];

const all_appointments = [["Dr-S","New York","Dr.Salazar"],["Dr-C","Austin","Dr.Connors"],["Dr-J","Austin","Dr.Johnson"],["Dr-S","New York","Dr.Salazar"],["Dr-P","San Juan","Dr.Pearson"],["Dr-J","Austin","Dr.Johnson"]];
 
const result1 = queued_Dr
  .map((queu) => all_appointments
    .find((appointment) => appointment.at(-1) === queu)
    .at(0));
    
console.log(result1);


const result2 = queued_Dr
  .map((queu) => {
    const [abbr, name] =  queu.split('.');
    return `${abbr}-${name.at(0)}`;
  });
  
console.log(result2);
.as-console-wrapper {max-height: 100% !important; top: 0}

关于javascript - 将数组中的数据连接到对象以通过中间人转换其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70764604/

相关文章:

javascript - jQuery Plugin - 深度选项修改

ios - Swift 中 "Accessing Subscripts of Optional Type"的说明

python - 如何从数据帧中获取数组或列表(其中 python 读取为 str 格式类型)?

c++ - gsl_vector 有 count_if 函数吗? C/C++

javascript - 如何使用 javascript/jquery 从嵌套列表生成嵌套的 json 对象

javascript - 为什么此函数打印 "undefined undefined"作为联系人姓名,并添加 “new Object” ?

javascript - 如何在 JavaScript 中制作具有效果的文本 "pop out"

javascript - 将 d3 slider 对象移动到特定位置

javascript - Mongoose : ".find(...).exec(...).then(...).catch(...).finally is not a function"使用 Bluebird ?

javascript - 使用 javascript 和 jquery 排列数组元素