簡體   English   中英

將數組值與對象進行比較

[英]compare array values with objects

我有一個看起來像的數組

positions = [{id: "pos1", name:"pos1"}, {id: "pos2", name:"pos2"}]

然后我有一個具有以下結構的對象

paritcipants = {pos1:[{salary:1000}],pos3:[{salary:1500}]}

所以我想檢查一下

  • 如果每個位置項的 id 都作為參與者的鍵存在,則保留它。
  • 如果沒有,則在具有該參與者 ID 的參與者下創建一個新數組。
  • 如果其他數組與任何位置 ID 不匹配,則刪除它們。

您可以使用函數映射進行過濾。

const paritcipants = {pos1:[{salary:1000}],pos3:[{salary:1500}]};
const positions = [{id: "pos1", name:"pos1"}, {id: "pos2",name:"pos2"}];

positions.map(item => console.log(paritcipants[item.id]));
// pos1 => [{salary: 1000}]
// pos2 => undefined

Object.keys(paritcipants); // ["pos1", "pos3"]

更多關於地圖:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

您可以遍歷數組並執行添加和刪除所需元素的邏輯。 我添加了內嵌評論,請檢查並告訴我:

 let positions = [{id: "pos1", name:"pos1"}, {id: "pos2", name:"pos2"}, {id: "pos4", name:"pos4"}] let paritcipants = {pos1:[{salary:1000}],pos3:[{salary:1500}]}; debugger; // Retrieve the keys of paritcipants ['pos1', 'pos3'] const paritcipantsKeys = Object.keys(paritcipants); /* Iterate over positions and check if they exist in paritcipants if they are not in it then push it. else remove it from keys array so that you can know which are extra keys in paritcipants */ for (const position of positions) { if( paritcipantsKeys.indexOf(position.id) === -1) { paritcipants[position.id] = [{salary: 1000}]; } else { paritcipantsKeys.splice(paritcipantsKeys.indexOf(position.id), 1) } } // Remove extra keys from paritcipants for(const paritcipantsKey of paritcipantsKeys) { delete paritcipants[paritcipantsKey]; } console.log(paritcipants);

如果我理解正確的話。 這是:

 const positions = [{id: "pos1", name:"pos1"}, {id: "pos2", name:"pos2"}]; const paritcipants = {pos1:[{salary:1000}],pos3:[{salary:1500}]} let newParticipants = {}; for(const position of positions) { newParticipants[position.id] = paritcipants[position.id] || []; } console.log(newParticipants); // newParticipants => {pos1:[{salary: 1000}],pos2: []}

請參考以下代碼。

 var positions = [{id: "pos1", name:"pos1"}, {id: "pos2", name:"pos2"}]; var participants = {pos1:[{salary:1000}],pos3:[{salary:1500}]}; var mathcedkeys = true; for(var i = 0; i < positions.length ; i++){ var key = positions[i].id; if(!participants[key]){ participants[key] = [{salary : 3000}]; } } for (var key in participants) { for(var i = 0; i < positions.length ; i++){ if(key == positions[i].id){ mathcedkeys = true; break; } else{ mathcedkeys = false; } } if(!mathcedkeys) delete participants[key]; } console.log(participants);

暫無
暫無

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

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