在添加到结果数组之前,请检查值是否存在

check if value exists before adding to result array

本文关键字:检查 是否 存在 添加 结果 数组      更新时间:2023-09-26

我正在循环一些数据,并创建一个新的数组,如下所示:

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

我只想包括d.note,如果它是一个值。数据中有很多对象没有此字段。我把这个条件放在哪里?我总是犯错误。思想受到赞赏。

替换此行

country[d.year] = d.value + " <span class='note'>" + d.note + "</span>", 
  countries[d.country]['note'] = d.note,
        countries[d.country]['GDP'] = d.gdp,
    countries[d.country].Country = d.country;

带有

if ( d.note )
{
  country[d.year] = d.value + " <span class='note'>" + d.note + "</span>";
  countries[d.country]['note'] = d.note;
}
countries[d.country]['GDP'] = d.gdp;
countries[d.country].Country = d.country;