![](/img/trans.png)
[英]How do I `.filter()` an array/object and return a new array with the original keys and not as an indexed array/object as filter return?
[英]How to filter and array and return new array of objects with indexed values?
給定數組const vals = [1, 2, 3, 4, 5, 6, 7, 8, 9];
如何過濾並返回一個新的索引鍵/值對對象數組,例如:
const vals = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// My fail attempt using filter()
let obj = vals.filter((n, i) => {
return new Object({ i: n % 2 });
});
return obj;
// expected result [{1:2}, {3:4}, {5:6}, {7:8}]
我需要保留索引值,因為我將使用不同的標准過濾 2 個不同的 arrays 並稍后將它們關聯起來。
按照評論中的建議,使用map()
更新第二次嘗試
let obj = vals.map((n, i) => {
if (n % 2) {
return { [i]: n };
}
});
給我以下內容: [{0:1}, undefined, {2:3}, undefined, {4:5}, undefined, {6:7}, undefined, {8:9}]
要獲取{ key: value }
對象的列表,其中key
是索引,並且值只有偶數,沒有奇數,您可以這樣做:
const vals = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const result = vals.map((v, i) => [i, v]).filter(([_, v]) => v % 2 == 0).map(([i, v]) => ({ [i]: v })); console.log(result);
使用第一個map
,您可以列出[[0, 1], ...]
對以保存索引以供以后使用。
然后過濾索引值對,以便只保留偶數值。
然后將這些對打包到另一個map
中的 object 中。
這可以通過使用reduce
的單次迭代更有效地完成:
const vals = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const result = vals.reduce((a, v, i) => { if (v % 2 == 0) { a.push({ [i]: v }); } return a; }, []); console.log(result);
Youn 可以嘗試簡單for
循環或reduce
function
let arr = [];
for(let i = 0; i<vals.length-1;i += 2)
{
let obj={};
obj[vals[i]]=vals[i+1];
arr.push(obj);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.