сравнить значения массива с объектами - PullRequest
0 голосов
/ 25 февраля 2020

У меня есть массив, который выглядит как

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

Тогда у меня есть объект, который имеет следующую структуру

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

Поэтому я хочу проверить

  • Если идентификатор каждого элемента позиции существует в качестве ключа участника, то сохраните его.
  • Если нет, то создайте новый массив под участниками с идентификатором этого участника.
  • Удалите другие массивы, если они не не соответствует ни одной позиции id.

Ответы [ 4 ]

1 голос
/ 25 февраля 2020

Вы можете использовать карту функций для фильтрации.

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

0 голосов
/ 25 февраля 2020

Пожалуйста, обратитесь ниже код.

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);
0 голосов
/ 25 февраля 2020

Если я вас правильно понял. Вот это:

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: []}
0 голосов
/ 25 февраля 2020

Вы можете l oop через массив и выполнить логи c, чтобы добавить и удалить нужные элементы. Я добавил встроенные комментарии, пожалуйста, проверьте и дайте мне знать:

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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...