javascript - 找到数组中键的所有现有值,从另一个数组中打印相应的数据

标签 javascript

我有一个 javascript 对象数组,其中一些对象有一个名为“note”的键。其他人没有这个属性。

我从 javascript 数组创建了一个 html 表格,其中(如果可用)注释编号附加到与对象的年份和国家相对应的表格单元格中的主要值。

我想根据每个注释的值在表格下方打印相应的定义。这些定义将来自一个单独的 js 数组——我已经包含了一个摘录。总共有大约 70 个定义,我只想打印表中存在“note”值的定义。这是它的屏幕截图:

enter image description here

我有点陷入思考如何做到这一点。有什么想法吗?我很感激!

Here is a jsfiddle.

完整代码如下:

<!DOCTYPE html>
<html>
<head>
    <style>
        body{
            font-family:Arial, sans-serif;
            font-size:14px;
        }
        table{
            border-spacing:0;
            padding:0;
        }
        #buildcontent{
            margin-left:100px;
            margin-top:20px;
            margin-right:100px;
        }
        #buildcontent table#years{
            clear:both;
        }
        #buildcontent table#countries{
            width:100%;
        }
        thead#years td{
            border-top:1px solid #ddd;
          border-bottom:0px;
          font-weight:bold;
            padding-top:3px;
            height:18px;
            padding-left:5px;
            padding-right:35px;
        }
        th{
          text-align:left;
          font-weight:normal !important;
          border-top:1px solid #ddd;
          border-left:1px solid #ddd;
          border-bottom:1px solid #ddd;
            height:25px;
            padding-left:5px;
            width: 90px;
        }
        td{
          border:1px solid #ddd;
            width:30px;
            height:25px;
            padding-left:5px;
        }
        tr.row-odd,
        .row-odd{
            background: #eee;
        }
        .note{
            color:steelblue;
            font-size:10px;
        }
    </style>
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <title>table with notes</title>
</head>
<body>
    <div id="content">
    </div>
<script>

fullData = [
    {
        "id": 103006,
        "iso3": "AFG",
        "country": "Afghanistan",
        "year": 2014,
        "value": 3.23,
        "note": 70011
    },
    {
        "id": 103006,
        "iso3": "ALB",
        "country": "Albania",
        "year": 2014,
        "value": 9.256,
        "note": 69011
    },
    {
        "id": 103006,
        "iso3": "DZA",
        "country": "Algeria",
        "year": 2014,
        "value": 7.611,
        "note": 69011
    },
    {
        "id": 103006,
        "iso3": "AND",
        "country": "Andorra",
        "year": 2014,
        "value": 9.582,
        "note": 69111
    },
    {
        "id": 103006,
        "iso3": "AGO",
        "country": "Angola",
        "year": 2014,
        "value": 4.726,
        "note": 69011
    },
    {
        "id": 103006,
        "iso3": "ATG",
        "country": "Antigua and Barbuda",
        "year": 2014,
        "value": 9.236,
        "note": 69011
    },
    {
        "id": 103006,
        "iso3": "ARG",
        "country": "Argentina",
        "year": 2014,
        "value": 9.834,
        "note": 69411
    },
    {
        "id": 103006,
        "iso3": "ARM",
        "country": "Armenia",
        "year": 2014,
        "value": 10.87,
        "note": 70011
    },
    {
        "id": 103006,
        "iso3": "AUS",
        "country": "Australia",
        "year": 2014,
        "value": 12.963
    },
    {
        "id": 103006,
        "iso3": "AUT",
        "country": "Austria",
        "year": 2014,
        "value": 10.834
    },
    {
        "id": 103006,
        "iso3": "AZE",
        "country": "Azerbaijan",
        "year": 2014,
        "value": 11.16
    },
    {
        "id": 103006,
        "iso3": "BHS",
        "country": "Bahamas",
        "year": 2014,
        "value": 10.945
    },
    {
        "id": 103006,
        "iso3": "BHR",
        "country": "Bahrain",
        "year": 2014,
        "value": 9.419
    },
    {
        "id": 103006,
        "iso3": "BGD",
        "country": "Bangladesh",
        "year": 2014,
        "value": 5.073
    },
    {
        "id": 103006,
        "iso3": "BRB",
        "country": "Barbados",
        "year": 2014,
        "value": 10.457
    },
    {
        "id": 103006,
        "iso3": "BLR",
        "country": "Belarus",
        "year": 2014,
        "value": 11.977
    },
    {
        "id": 103006,
        "iso3": "BEL",
        "country": "Belgium",
        "year": 2014,
        "value": 11.273
    },
    {
        "id": 103006,
        "iso3": "BLZ",
        "country": "Belize",
        "year": 2014,
        "value": 10.488
    },
    {
        "id": 103006,
        "iso3": "BEN",
        "country": "Benin",
        "year": 2014,
        "value": 3.3
    },
    {
        "id": 103006,
        "iso3": "BTN",
        "country": "Bhutan",
        "year": 2014,
        "value": 3.01
    },
    {
        "id": 103006,
        "iso3": "BOL",
        "country": "Bolivia (Plurinational State of)",
        "year": 2014,
        "value": 8.154
    },
    {
        "id": 103006,
        "iso3": "BIH",
        "country": "Bosnia and Herzegovina",
        "year": 2014,
        "value": 8.326
    },
    {
        "id": 103006,
        "iso3": "BWA",
        "country": "Botswana",
        "year": 2014,
        "value": 8.87
    },
    {
        "id": 103006,
        "iso3": "BRA",
        "country": "Brazil",
        "year": 2014,
        "value": 7.66
    },
    {
        "id": 103006,
        "iso3": "BRN",
        "country": "Brunei Darussalam",
        "year": 2014,
        "value": 8.77
    },
    {
        "id": 103006,
        "iso3": "BGR",
        "country": "Bulgaria",
        "year": 2014,
        "value": 10.566
    },
    {
        "id": 103006,
        "iso3": "BFA",
        "country": "Burkina Faso",
        "year": 2014,
        "value": 1.374
    },
    {
        "id": 103006,
        "iso3": "BDI",
        "country": "Burundi",
        "year": 2014,
        "value": 2.686
    },
    {
        "id": 103006,
        "iso3": "CPV",
        "country": "Cabo Verde",
        "year": 2014,
        "value": 4.683
    },
    {
        "id": 103006,
        "iso3": "KHM",
        "country": "Cambodia",
        "year": 2014,
        "value": 4.369
    },
    {
        "id": 103006,
        "iso3": "CMR",
        "country": "Cameroon",
        "year": 2014,
        "value": 5.96
    },
    {
        "id": 103006,
        "iso3": "CAN",
        "country": "Canada",
        "year": 2014,
        "value": 13.004
    },
    {
        "id": 103006,
        "iso3": "CAF",
        "country": "Central African Republic",
        "year": 2014,
        "value": 4.224
    },
    {
        "id": 103006,
        "iso3": "TCD",
        "country": "Chad",
        "year": 2014,
        "value": 1.929
    },
    {
        "id": 103006,
        "iso3": "CHL",
        "country": "Chile",
        "year": 2014,
        "value": 9.787
    },
    {
        "id": 103006,
        "iso3": "CHN",
        "country": "China",
        "year": 2014,
        "value": 7.54
    },
    {
        "id": 103006,
        "iso3": "COL",
        "country": "Colombia",
        "year": 2014,
        "value": 7.35
    },
    {
        "id": 103006,
        "iso3": "COM",
        "country": "Comoros",
        "year": 2014,
        "value": 4.602
    },
    {
        "id": 103006,
        "iso3": "COG",
        "country": "Congo",
        "year": 2014,
        "value": 6.09
    },
    {
        "id": 103006,
        "iso3": "COD",
        "country": "Congo (Democratic Republic of the)",
        "year": 2014,
        "value": 6.01
    },
    {
        "id": 103006,
        "iso3": "CRI",
        "country": "Costa Rica",
        "year": 2014,
        "value": 8.368
    },
    {
        "id": 103006,
        "iso3": "CIV",
        "country": "Côte d'Ivoire",
        "year": 2014,
        "value": 4.26
    },
    {
        "id": 103006,
        "iso3": "HRV",
        "country": "Croatia",
        "year": 2014,
        "value": 11.027
    },
    {
        "id": 103006,
        "iso3": "CUB",
        "country": "Cuba",
        "year": 2014,
        "value": 11.514
    },
    {
        "id": 103006,
        "iso3": "CYP",
        "country": "Cyprus",
        "year": 2014,
        "value": 11.619
    },
    {
        "id": 103006,
        "iso3": "CZE",
        "country": "Czech Republic",
        "year": 2014,
        "value": 12.32
    }
];
definitions = [
    {
        "note": 69111,
        "def": "This is the first definition."
    },
    {
        "note": 70011,
        "def": "This is the second definition."     
    }
];

        // add years for select indicator
        var nestyr = d3.nest()
            .key(function(d) { return d.year; })
            .sortKeys(d3.ascending)
            .map(fullData);

        var yearstring = Object.keys(nestyr);

        var width = 200, height = 25;
        var minInd = d3.min(fullData, function(d) { return d.value;} )
        var maxInd = d3.max(fullData, function(d) { return d.value;} )

        var tableData = [],
            countries = {};
            fullData.forEach(function (d) {
            var country = countries[d.country];
            if (!country) {
                tableData.push(country = countries[d.country] = {});
                }
                if ( d.note ){
                      country[d.year] = d.value + " <span class='note'>" + d.note + "</span>";
                      countries[d.country]['note'] = d.note;
                } else{
                        country[d.year] = d.value;
                }
            countries[d.country].Country = d.country;
        });

        yearstring.unshift("Country");

        // render the table(s)
        tabulate(tableData, yearstring);

function tabulate(newData, columns) {
            var table = d3.select('#content').append('table')
            var thead = table.append('thead')
            var tbody = table.append('tbody');

      var type = d3.nest()
              .key(function(d) { return d.country; })
                .sortKeys(d3.ascending)
              .entries(fullData);

            // append the header row
            thead.append('tr')
              .selectAll('th')
              .data(columns).enter()
              .append('th')
                .text(function (column) { return column; });

            // create a row for each object in the data
            var rows = tbody.selectAll('tr')
              .data(newData)
              .enter()
              .append('tr');

              // add stripes to the table
            rows.attr("class", function(d, i){ if (i++ % 2 === 0){return 'row-even'}else {return 'row-odd'}});

            // create a cell in each row for each column
            var cells = rows.selectAll('td')
              .data(function (row) {
                return columns.map(function (column) {
                  return {column: column, value: row[column]};
                });
              })
              .enter()
              .append('td')
                    .attr("class", function (d,i) { return columns[i]; })
                .html(function (d) { return d.value; });

          return table;
};


</script>
</body>
</html>

最佳答案

如果我们为笔记改用对象而不是数组,事情会变得更短、更容易、更高效。这样您就可以轻松查询有问题的 key 。

definitions = [
    {
        "note": 69111,
        "def": "This is the first definition."
    },
    {
        "note": 70011,
        "def": "This is the second definition."     
    }
];

definitions = {
      "69111": "This is the first definition.",
        "70011": "This is the second definition."
};

当您对笔记执行检查(并找到一个)时,将其用作对象的键。 首先,让我们在循环外设置一个包含脚注的字符串,然后我们可以在循环内填充脚注。

然后,为了防止生成同一个笔记的多个实例(国家/地区共享相同的笔记键),我们应该在循环之外列出我们拥有的笔记,每次我们都会更新它添加备注。

然后我们可以将所需的文本添加到保存笔记的字符串中(如果它确实存在),当循环结束时,将其附加到内容中。

var notes="";   // this holds our string, containing all the needed footnotes, but not more
var added=[];   // a list of the footnotes we've already included

...和内部循环:

if ( d.note ){
country[d.year] = d.value + " <span class='note'>" + d.note + "</span>";
countries[d.country]['note'] = d.note;
if(added.indexOf(d.note)==-1){  // only when we HAVEN'T added it yet...
if(undefined!=definitions[d.note]){   // ...and there is actually a note available...
notes+=definitions[d.note]+"<br />";  // add it to the string
added.push(d.note);  // add the key to the list, so we won't add it again later
}
}

这有效: http://jsfiddle.net/svArtist/txc16240/

关于javascript - 找到数组中键的所有现有值,从另一个数组中打印相应的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34096058/

相关文章:

javascript - 将字符串数组从 Groovy 传递到 Javascript

javascript - 使用名称过滤器计算对象属性的数量

php - 将 PHP 数组值放入 javascript 数组中?

javascript - 无法读取 Node.js 中的 castArrayFilters 处未定义的属性 'castForQuery'

javascript - 编译好的脚本应该放在 React 中的什么位置?

Javascript 图像褪色?

javascript - 在 D3.js 中预先计算和设置节点的初始位置

javascript - 在 PyroCMS 中使用 jQuery 更新下拉列表的选定值

javascript - Threejs 添加带有轨道控件的鼠标事件

javascript - 让条形图行在 D3 中显示不同转换率的任何方法