循环遍历不可变js

时间:2017-03-17 15:31:52

标签: javascript iteration immutable.js

我是javascript的新手,我想使用不可变的js完成一项任务。 我有这样的地图:

const clients = Map({
        "c1": {
            "id": "c1",
            "isLegalEntity": false,
            "wantsEstatements": true,
            "portfolios": {
                "a": {
                    "id": "a",
                    "type": "Cash"
                },
                "b": {
                    "id": "b",
                    "type": "Margin"
                }
            }
        },
        "c2": {
            "id": "c2",
            "isLegalEntity": false,
            "wantsEstatements": true,
            "portfolios": {
                "e": {
                    "id": "e",
                    "type": "Cash"
                },
                "f": {
                    "id": "f",
                    "type": "Margin"
                }
            }
        }
    })

我想创建三个表。第一个表格将包含" c1"和" c2"从我阅读的文档中得到的值我使用了clients.keys()属性。 另一个表必须包含所有这样的投资组合ID:[" e"," f"],最后一个表格必须包含所有投资组合类型:[" cash& #34;," margin"]但我不知道如何从文档中做到这一点。你知道吗?

1 个答案:

答案 0 :(得分:1)

我不确定你拥有数组后想要做什么,所以我只是在这个例子中将它们显示在HTML标签中。但是,这应该向您展示如何创建您正在寻找的每个阵列。第一步是使用Array.from(clients.keys())获取客户端ID数组;呼叫。在此之后,您在clients.getIn()调用中使用客户端ID,该调用返回每个客户端的标准javascript对象。在此之后,您可以使用标准的javascript对象访问方法从客户端对象构建所需的数组。



var clients = Immutable.Map({
  "c1": {
    "id": "c1",
    "isLegalEntity": false,
    "wantsEstatements": true,
    "portfolios": {
      "a": {
        "id": "a",
        "type": "Cash"
      },
      "b": {
        "id": "b",
        "type": "Margin"
      }
    }
  },
  "c2": {
    "id": "c2",
    "isLegalEntity": false,
    "wantsEstatements": true,
    "portfolios": {
      "e": {
        "id": "e",
        "type": "Cash"
      },
      "f": {
        "id": "f",
        "type": "Margin"
      }
    }
  }
});

function logArray(arr) {
  var str = "[";
  for (var i = 0; i < arr.length; i++) {
    str += arr[i];
    if (i < arr.length - 1) str += ",";
  }
  str += "]"
  document.getElementById("info").innerHTML += str + "<br>";
}

var client_id_array = Array.from(clients.keys());
logArray(client_id_array);
for (var i = 0; i < client_id_array.length; i++) {
  var obj = clients.getIn([client_id_array[i]]);
  var portfolio_array = Object.keys(obj.portfolios);
  logArray(portfolio_array);
  var types = [];
  for (j = 0; j < portfolio_array.length; j++) {
    types[j] = obj.portfolios[portfolio_array[j]].type;
  }
  logArray(types);
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.5/immutable.js"></script>

<div id="info"></div>
&#13;
&#13;
&#13;