繁体   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