簡體   English   中英

在JavaScript中迭代對象

[英]Iterating Through An Object In JavaScript

如果我有一個對象,就像這樣:

const test = [
  { x: 'A', y:'1' },
  { x: 'A', y:'2' },
  { x: 'B', y:'1' },
  { x: 'A', y:'3' },
  { x: 'C', y:'1' },
];

我怎樣才能通過它,從x中找到順序[A, B, C] ,其中[A, B, C]屬於一個唯一的y?

到目前為止,我嘗試使用for循環迭代對象,按順序查找所有'A','B','C',但我不能確保它們都屬於同一個y項。

將數組轉換為數組對象,首先只對應一個特定的y

 const test = [ { x: 'A', y:'1' }, { x: 'A', y:'2' }, { x: 'B', y:'1' }, { x: 'A', y:'3' }, { x: 'C', y:'1' }, ]; const reducedToYs = test.reduce((accum, { x, y }) => { accum[y] = (accum[y] || '') + x; return accum; }, {}); const found = Object.entries(reducedToYs) .find(([y, str]) => str.includes('ABC')); console.log('y: ' + found[0] + ', entire string: ' + found[1]); 

創建一個獲取目標Y值的函數。 循環遍歷測試數組並將y值與目標值進行比較,如果匹配,則將x值推入數組。 然后返回該數組。

如果需要一個字符串(“ABC)”,那么不是創建一個數組而是創建一個字符串並將x值附加到它以構建隨后返回的字符串。

 const test = [ { x: 'A', y:'1' }, { x: 'A', y:'2' }, { x: 'B', y:'1' }, { x: 'A', y:'3' }, { x: 'C', y:'1' }, ]; function testValue(str) { let xArray = []; test.forEach(function(item) { if(item['y'] === str) {xArray.push(item['x'])} }) return xArray; } console.log(testValue('1')) // gives ["A", "B", "C"] 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM