簡體   English   中英

使用鍵數組過濾對象數組並提取其屬性

[英]Filter an array of objects and extract its property by using an array of keys

我有這個問題,我不能纏住我的頭,

如果輸入代碼,會更好。

//Array of objects sample
var objects = [{id:1, name:'test1'}, {id:2, name:'test2'}, {id:3, name: 'test3'}, {id:4, name:'test4'}];
var arrayOfKeys = [3,1,4];

//extract object name property if its id property is equivalent to one of arrayOfKeys [3,1] 
//var arrayOfKeys = [3,1,4];
//output sample: extractedName=['test3','test1','test4'];

我一直在使用過濾器和地圖,但無濟於事,還嘗試在地圖內嵌套過濾器,以獲取數組數組,並且內部是單個對象。

您可以映射對象,也可以映射想要的鍵以獲得名稱。

 var objects = [{ id: 1, name: 'test1' }, { id: 2, name: 'test2' }, { id: 3, name: 'test3' }], arrayOfKeys = [3, 1], result = arrayOfKeys.map((map => id => map.get(id).name)(new Map(objects.map(o => [o.id, o])))); console.log(result); 

我假設您需要將數組編號映射到id屬性? 這是代碼,您find在其中map數字並在數組內部find以處理對象數組中沒有此類id情況:

 var objects = [{id:1, name:'test1'}, {id:2, name:'test2'}, {id:3, name: 'test3'}]; var arrayOfKeys = [3,1]; var res = arrayOfKeys.map(key => { var found = objects.find(o => o.id == key); return found ? found.name : false; }) console.log(res) 

 let objects = [{id:1, name:'test1'}, {id:2, name:'test2'}, {id:3, name: 'test3'}, {id:4, name:'test4'}], arrayOfKeys = [3,1,4]; let result = objects.reduce((res, obj) => { // loop over the array of objects let index = arrayOfKeys.indexOf(obj.id); // check if the current object's id is in the array of keys if(index !== -1) { // if it's there res.push(obj.name); // then add the current object's name to the result array arrayOfKeys.splice(index, 1); // remove its id from the array of keys so we won't search for it again (optional, slightly better than leaving it there) } return res; }, []); console.log(result); 

我認為您在使用篩選器的過程中處於正確的軌道。 您可以使它變得可讀和簡潔。

 var objects = [{id: 1,name: 'test1'}, {id: 2,name: 'test2'}, {id: 3,name: 'test3'}, {id: 4,name: 'test4'}], arrayOfKeys = [3, 1, 4]; var result = objects.filter((x, i) => { if (arrayOfKeys.some(k => x.id === k)) { return true; } }) console.log(result.map(x=>x.name)); 

更短的東西! 將會

 var objects = [{id: 1,name: 'test1'}, {id: 2,name: 'test2'}, {id: 3,name: 'test3'}, {id: 4,name: 'test4'}],arrayOfKeys = [3, 1, 4]; var result = objects.filter((x, i) => arrayOfKeys.some(k => x.id === k)); console.log(result.map(x=>x.name)); 

暫無
暫無

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

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