[英]compare array values with objects
我有一個看起來像的數組
positions = [{id: "pos1", name:"pos1"}, {id: "pos2", name:"pos2"}]
然后我有一個具有以下結構的對象
paritcipants = {pos1:[{salary:1000}],pos3:[{salary:1500}]}
所以我想檢查一下
您可以使用函數映射進行過濾。
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.