[英]Filtering JavaScript array of objects by property of an object and removing duplicates
[英]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:”部分。
我尝试使用从以前对其他人的问题的答案( 如何从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);
但它在控制台中返回“未定义im”。
任何帮助是极大的赞赏!
您可以使用数组map
功能。 基本上,我们遍历数组。 如果该项目具有.re
属性,则仅采用该值。 如果没有.re
属性,则该值保持不变。
我们可以使用三元运算符和箭头函数以简写形式(如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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.