在JavaScript中动态填充对象数组的问题

在javascript中动态填充对象数组时,我遇到了一个问题。我有以下示例数据:

在JavaScript中动态填充对象数组的问题

我必须用上面的数据填充以下数组:

c1_Arr = [];
c2_Arr = [];

var torontoObj = { arName: 'تورونتو',enName: 'Totonto',value: 0 };
var parisObj = { arName: 'باريس',enName: 'Paris',value: 0 };
var londonObj = { arName: 'لندن',enName: 'London',value: 0 };

现在,我正在遍历数据以将数据值设置为:

var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
    var data = results.features[i].attributes;

    parisObj.value = data.Paris;
    londonObj.value = data.London;
    torontoObj.value = data.Toronto;

    if (data.Ind_ID === 101) {
        c1_Arr.push(parisObj);
        c1_Arr.push(londonObj);
        c1_Arr.push(torontoObj);
    }
}
console.log(c1_Arr);

我正在控制台中获取此数据:

在JavaScript中动态填充对象数组的问题

我在这里获取对象的值,即 Ind_ID = 102 ,而不是 Ind_ID = 101 (第一个对象)的对象值。

  

如何使用Ind_ID获取所需对象的值?

duanchongxixi 回答:在JavaScript中动态填充对象数组的问题

问题是因为即使那里有if条件,但您正在更新循环中对象的值,并且由于已经将它们推入了对象,所以您仍然在主要对象中具有引用。他们被覆盖了。

在循环内创建3个对象(torontoObj等)。

,

引用在第二次迭代中得到更新( Ind_ID 为102)

您宁愿这样做

var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
    var data = results.features[i].attributes;

    if (data.Ind_ID === 101) {
        parisObj.value = data.Paris;
        londonObj.value = data.London;
        torontoObj.value = data.Toronto;
        c1_Arr.push(parisObj);
        c1_Arr.push(londonObj);
        c1_Arr.push(torontoObj);
    }
}
console.log(c1_Arr);
,

即使在Paris循环中设置了对象值,您的对象值也会得到更新,这仅仅是因为,您并没有限制对其进行更新。

您可能可以执行以下两项操作之一:

  1. 更简单的一个:

仅当LondonToronto时,才提取data的{​​{1}},Ind _ID101字段的值。

像这样:

var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
    var data = results.features[i].attributes;

    if (data.Ind_ID === 101) {
        parisObj.value = data.Paris;
        londonObj.value = data.London;
        torontoObj.value = data.Toronto;
        c1_Arr.push(parisObj);
        c1_Arr.push(londonObj);
        c1_Arr.push(torontoObj);
    }
}
console.log(c1_Arr);
  1. 更优雅的一个:

提取仅与您的条件匹配的数组元素,即filter

    var resultCount = results.features.length;
    var data = results.features.filter(feature => feature.attributes.Ind_ID === 101);
    parisObj.value = data[0].Paris;
    londonObj.value = data[0].London;
    torontoObj.value = data[0].Toronto;
    console.log(c1_Arr);
本文链接:https://www.f2er.com/3119583.html

大家都在问