Объединяйте равные объекты, используя функции высокого порядка - PullRequest
0 голосов
/ 23 мая 2018

Я бы хотел "объединить" объекты из массива, если они имеют значения, равные друг другу.

Вот пример:

"relations_entities": [
  {
    "relation": {
      "label": string,
      "inEntityId": string,
      "outEntityId": string,
      "proof": [
        {
          "text": string,
          "confidence": number,
        }
      ],
    },
    "entity": {
      "entityId": string,
      "label": string,
      "text": string,
    },
  },
  {
    "relation": {
      "label": string,
      "inEntityId": string,
      "outEntityId": string,
      "proof": [
        {
          "text": string,
          "confidence": number,
        }
      ],
    },
    "entity": {
      "entityId": string,
      "label": string,
      "text": string,
    },
  },
]

и если relations_entities[0].relation.label и relations_entities[0].entity.label равно relations_entities[0].relation.label и relations_entities[0].entity.label

Тогда мне нужно, чтобы этот объект был:

"relations_entities": [
  {
    "relation": {
      "label": string,
      "inEntityId": string,
      "outEntityId": string,
      "proof": [
        {
          "text": string,
          "confidence": number,
        },
        {
          "text": string,
          "confidence": number,
        }
      ],
    },
    "entity": {
      "entityId": string,
      "label": string,
      "text": string,
    },
  },
]

Два доказательства объединены.

Я пытался реализовать этоповедение с использованием фильтров, но я сошел с ума.

Может быть, с помощью библиотеки lodash?

Есть идеи?

Ответы [ 2 ]

0 голосов
/ 23 мая 2018

Вот решение, использующее функции жирной стрелки es6, его можно улучшить, передав ключи, которые вы хотите проверить.Если вам нужна эта функциональность, я не против добавить ее в ваш ответ для полноты.

var relations_entities = [
  {
    "relation": {
      "label": 'a',
      "inEntityId": '123',
      "outEntityId": '123',
      "proof": [
        {
          "text": '123',
          "confidence": '123',
        }
      ],
    },
    "entity": {
      "entityId": '123',
      "label": '123',
      "text": '123',
    },
  },
  {
    "relation": {
      "label": 'b',
      "inEntityId": '321',
      "outEntityId": '321',
      "proof": [
        {
          "text": '321',
          "confidence": '321',
        }
      ],
    },
    "entity": {
      "entityId": '321',
      "label": '123',
      "text": '321',
    },
  },
  {
    "relation": {
      "label": 'c',
      "inEntityId": '321',
      "outEntityId": '321',
      "proof": [
        {
          "text": '321',
          "confidence": '321',
        }
      ],
    },
    "entity": {
      "entityId": '321',
      "label": '123',
      "text": '321',
    },
  },
  {
    "relation": {
      "label": 'b',
      "inEntityId": '321',
      "outEntityId": '321',
      "proof": [
        {
          "text": '321',
          "confidence": '321',
        }
      ],
    },
    "entity": {
      "entityId": '321',
      "label": '123',
      "text": '321',
    },
  }
]

const compareEntities = (oldEntities) => {
  // early breakout if there is just one element
  if (oldEntities.length === 0) {
    return oldEntities
  }
  
  // here we iterate through each of the passed in entities
  var newEntities = oldEntities.filter((entity, index, entities) => {
    // set the internal counter to 1 higher than the filtered counter
    // (the next object along)
    var i = index + 1
    const relationlabel = entity.relation.label
    const entityLabel = entity.entity.label

    // iterate through each remaining entity and remove from array if there is a match
    while (i < entities.length) {
      const relationLabelIsEqual = relationlabel === entities[i].relation.label
      const entityLabelIsEqual = relationlabel === entities[i].relation.label
      if (relationLabelIsEqual && entityLabelIsEqual) {
        i = index + 1
        return false
      }
      // if there is no match we just want to move onto the next entity
      ++i
    }
    // if we have iterated through all entities then there was no match
    // - return it into the new array
    return true
  })
  return newEntities
}

console.log(compareEntities(relations_entities))

Вы также можете играть с репликой, которую я настроил

0 голосов
/ 23 мая 2018

Посмотрите на это:

let relations_entities = [
  {
    relation: {
      label: 'string',
      inEntityId: 'string',
      outEntityId: 'string',
      proof: [
        {
          text: 'string',
          confidence: 'number',
        }
      ],
    },
    entity: {
      entityId: 'string',
      label: 'string',
      text: 'string',
    },
  },
  {
    relation: {
      label: 'string',
      inEntityId: 'string',
      outEntityId: 'string',
      proof: [
        {
          text: 'string',
          confidence: 'number',
        }
      ],
    },
    entity: {
      entityId: 'string',
      label: 'string',
      text: 'string',
    },
  },
];

let merged = [];

relations_entities.forEach(el => {
  let found = false;  
  if (merged.length > 0) {
    merged.forEach(elM => {
      if (el.relation.label === elM.relation.label && !found) {
        elM.relation.proof = elM.relation.proof.concat(el.relation.proof);
        found = true;
      }
    });
  } 
  if (!found || merged.length === 0) {
    merged.push(el);
  }
});

console.log(merged);
...