javascript - 根据 ID 从一个数组获取另一数组的数据

标签 javascript arrays

情况或多或少是这样的:我得到一个数组(使用 JS)和一个对象(我们称之为 TASK),如下所示(它不是完整的数组,只是一个实例):

{
      "id": "28",
      "name": "sdfsdf",
      "progress": 80,
      "description": "",
      "code": "1",
      "level": 1,
      "status": "STATUS_SUSPENDED",
      "depends": "",
      "canWrite": true,
      "start": 1444341600000,
      "duration": 7,
      "end": 1445291999999,
      "startIsMilestone": 0,
      "endIsMilestone": 0,
      "collapsed": false,
      "assigs": [
        {
          "resourceId": 3,
          "otherStuff": xyz
        },
        {
          "resourceId": 2,
          "otherStuff": xyz
        }
      ],
      "hasChild": true
    }

我加载的另一个对象包含所有“资源”,在第一个数组中用“assigs”引用:[](我们称这些为资源):

[
  {
    "ID": "1",
    "name": "service | 1st resource we need",
    "unit": "pcs",
    "quantity": "10"
  },
  {
    "ID": "2",
    "name": "money | Office space",
    "unit": "hour",
    "quantity": "50"
  },
  {
    "ID": "3",
    "name": "product | Money for nothing...",
    "unit": "$",
    "quantity": "300"
  },
  {
    "ID": "4",
    "name": "people | Chovjek",
    "unit": "people",
    "quantity": "1"
  }
]

我用任务数据填充一些表单字段,但我根本无法弄清楚如何将任务与其资源“连接”。

最佳答案

如果我们谈论的是较新版本的 javascript,请像这样:

for(var task of tasks)
{
    for(var ass of task.assigns)
    {
        for(var res of resources)
        {
            if(res.ID === ass.resourceId.toString()) {
                //here res and ass match and you can do what you want
            }
        }
    }
}

在所有版本的 JS 中你都可以这样做

for(var i = 0; i < tasks.length; i++)
{
    for(var x = 0; x< tasks[i].assigns.length; x++)
    {
        for(var y = 0; y < resources.length; y++)
        {
            if(resources[y].ID === tasks[i].assigns[x].resourceId.toString()) {
                //here res and ass match and you can do what you want
            }
        }
    }
}

关于javascript - 根据 ID 从一个数组获取另一数组的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34309963/

相关文章:

javascript - 函数参数作为 json 键

ios - 如何从 swift 2.1 中的对象数组创建字典?

c++ - 在屏幕上显示 vector

php - 将数组分配给静态函数变量php

javascript - 创建颜色选择器

c# - 倒计时器?

javascript - 如何获取2个字符之间的值

javascript - 何时在 famo.us 中使用 #render 方法

Javascript 显示本地存储阵列中的数据问题

arrays - 使用速度 split() 将字符串拆分为数组似乎不起作用