[英]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.