删除数组中对象中的对象 javascript

removing objects in an object in an array javascript

我对这个问题做了一些研究。我正在尝试在控制台中操作一组计算值,如下所示:

{nodeVoltages: Array(11), totalPower: Array(1), xlength: Array(11)}
  nodeVoltages: Array(11)
    0:48
    1:47.71306060387108
    2:47.250273223993105
    3:46.59686907269243
    4:45.71876416434013
    5:44.53304242029258
    6:42.745236969423615
    7:Complex {re: 40.38334500994142, im:1.919295696316476, __ember1513267958317: "ember368"}
    8:Complex { re:39.55961661806138, im:3.8933604519196416, __ember1513267958317: "ember369"}

这个数组是通过我想出的一些数学动态创建的,所以我没有可以给你的输入数据。我试图让上面的数组看起来像这样:

{nodeVoltages: Array(11), totalPower: Array(1), xlength: Array(11)}
  nodeVoltages: Array(11)
    0:48
    1:47.71306060387108
    2:47.250273223993105
    3:46.59686907269243
    4:45.71876416434013
    5:44.53304242029258
    6:42.745236969423615
    7:40.38334500994142
    8:39.55961661806138

使用 mathjs,我能够评估我的表达式并使用 array.push 命令将值动态添加到数组中并显示它们。但是,一旦虚数值出现在我的数组结果中,我的代码就会中断。

如何从数组中删除这些虚数?换句话说,在将它们推送到显示的数组之前,我需要在它们开始出现时删除值的 "im:" 部分。

我尝试使用从之前对其他人问题 (How do I remove a particular element from an array in JavaScript?) 的回答中找到的一些代码来执行此操作,如下所示拼接命令:

      var nodeVoltage2 = parser.eval(expression2);

//checks if there are imaginary values and removes them

            if ("im" in nodeVoltage2) {
              nodeVoltage2.splice(2,1)
            }

//adds value to result array for analysis

      nodeVoltages.push(nodeVoltage2);

但是 returns 在控制台中 "im is not defined"。

非常感谢任何帮助!

可以使用数组map函数。 基本上,我们遍历数组。如果该项目有 .re 属性,我们只采用该值。如果没有.re 属性,我们保持原值。

我们可以在 shorthand 中使用三元运算符和箭头函数将其写成 result,或者我们可以将其写成稍微冗长但传统的方式,如 resultTwo

let data = [
    48
    ,47.71306060387108
    ,47.250273223993105
    ,46.59686907269243
    ,45.71876416434013
    ,44.53304242029258
    ,42.745236969423615
    ,{re: 40.38334500994142, im:1.919295696316476, __ember1513267958317: "ember368"}
    ,{ re:39.55961661806138, im:3.8933604519196416, __ember1513267958317: "ember369"}
]

let result = data.map((x) => x && x.re ? x.re : x);


let resultTwo = data.map(function(elem) {
    // First, we need to check that the array element is not null / undefined
    // We then need to check that it has a property called re that is also not null / undefined
    if (elem != null && elem.re != null) {
        // Just return the property we're interested in
        return elem.re;
    } else {
        // Return the element as is
        return elem;
    }
});

console.log(result);
console.log(resultTwo);