【问题标题】:Get the same value from another array and assign to object of arrays从另一个数组中获取相同的值并分配给数组对象
【发布时间】:2020-12-02 13:37:32
【问题描述】:

我有两个对象数组如下

          const arr1 = [
            {
              location_ID: 1,
              employee: "name",
              status: "available",
            },
            {
              location_ID: 2,
              employee: "name",
              status: "available",
            },
          ];

          const arr2 = [
            {
              assetLocation_ID: 1,
              location_Name: "Yangon",
            },
            {
              assetLocation_ID: 2,
              location_Name: "Mandalay",
            },
            {
              assetLocation_ID: 3,
              location_Name: "Magway",
            },
          ];

我正在尝试查找位置名称并通过location_IDarr1 中插入一个新字段,因此最终结果会是这样的

          const arr1 = [
            {
              location_ID: 1,
              employee: "name",
              location_Name: "Yangon",
              status: "available",
            },
            {
              location_ID: 2,
              employee: "name",
              location_Name: "Mandalay",
              status: "available",
            },
          ];

我已经在 arr1 中尝试了 for 循环,在 arr2 中尝试了 arr2.find,但是 arr1 的对象始终具有 ID 1 的位置,我在这里做错了什么?到目前为止,这是我的代码

          for (let i in arr1) {

            arr1[i].asset_Location = arr2.find((one) => {
              // one is always showing the first object of arr2
              return (arr1[i].location_ID = one.assetLocation_ID);
            }).location_Name;
    }

【问题讨论】:

  • 语法错误..这里应该是==arr1[i].location_ID = one.assetLocation_ID

标签: javascript


【解决方案1】:

您可以执行以下操作,

const result = arr1.map(item => {
  const index = arr2.findIndex(asset => asset.assetLocation_ID === item.location_ID);
  if(index > -1) {
      return {...item, location: arr2[index].location_Name};
  }
  return item;

或者如果你想知道你的代码有什么问题,

for (let i in arr1) {
    arr1[i].asset_Location = arr2.find((one) => {
       // we need to return true or false from this method. You were assigning `one.assetLocation_ID` to `arr1[i].location_ID` instead of comparing them.
       return arr1[i].location_ID === one.assetLocation_ID;
    }).location_Name;
}

要了解有关 find 方法的更多信息,请阅读 this 文章。

【讨论】:

    猜你喜欢
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2020-11-13
    • 1970-01-01
    相关资源
    最近更新 更多