获取对象数组的未定义值

时间:2020-03-03 01:34:44

标签: javascript

正在做

  const data = [{}];

  function doAddress(indirizzo) {
    indirizzo.forEach(function(item){
      var a = item[1];
      var location = item[0];
      let newObj = {};
      newObj.idValue = ids[a];
      newObj.addressValue = location;
      newObj.metalValue = metal[a];
      newObj.glassValue = glass[a];
      newObj.plasticValue = plastic[a];
      newObj.paperValue = paper[a];
      data.push(newObj);
    })
  }

然后尝试获得最高的金属价值:

  const highestMetalValueObj = data.sort((a, b) => b.metalValue - a.metalValue)[0];
  console.log("address " + highestMetalValueObj.addressValue + " has the highest metal value of " + highestMetalValueObj.metalValue);

控制台提供:

address undefined has the highest metal value of undefined

为什么我变得未定义并且不访问值?

Console.log数据给出:

0: {}
1: {idValue: 20, addressValue: "Corso Vittorio Emanuele, 1, 09017 Sant'Antioco SU, Italia", metalValue: 0.879, glassValue: 2.896, plasticValue: 1.365, …}
2: {idValue: 33, addressValue: "Via Giosuè Carducci, 15, 09017 Sant'Antioco SU, Italia", metalValue: 0.078, glassValue: 0.256, plasticValue: 0.098, …}
3: {idValue: 18, addressValue: "Via Castello, 5, 09017 Sant'Antioco SU, Italia", metalValue: 0.256, glassValue: 0.356, plasticValue: 0.085, …}
4: {idValue: 35, addressValue: "Via Marco Polo, 1, 09017 Sant'Antioco SU, Italia", metalValue: 0.356, glassValue: 0.156, plasticValue: 0.356, …}
5: {idValue: 26, addressValue: "Lungomare Amerigo Vespucci, 1, 09017 Sant'Antioco SU, Italia", metalValue: 0.321, glassValue: 0.085, plasticValue: 0.156, …}

1 个答案:

答案 0 :(得分:1)

这行可能不是您想要的:

const data = [{}];

这是从数组开始的,它是一个包含一个没有属性的对象的数组。您正在向其中推送更多项目,但是原始的空对象仍将在那里。排序后,您最有可能将其列为最重要的项目。

只需将您的数组作为一个空数组开始

const data = [];

此外,在控制台语句中,您正在寻址highestMetalValueObj.address,但是您的对象似乎没有该属性。您可能打算改用highestMetalValueObj.addressValue