Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

222
Visualizações
Simplest method to merge two objects using a Lens

I'm new to Ramda and trying to restrict myself to not resorting to vanilla JS methods for tasks like this while I adjust. I'm stuck on something that feels very simple. Ramda loses clarity for me as soon as I need to chain some things together like this.

I used R.groupBy to aggregate some other data into an object with some keys, I have a target object I'd like to merge this with - however the keys from the groupby are nested within it.

I can create a view with a lens on the target property to see the data transformed to match - I'm not quite sure how to do the reverse to apply the grouped data to the nested object.

let ungroupedData = [
  {"tag":"foo","id":99}, {"tag":"bar","id":33}, {"tag":"foo","id":14}, {"tag":"bar","id":26},
  {"tag":"baz","id":99}, {"tag":"qux","id":33}, {"tag":"foo","id":49}, {"tag":"bar","id":13}
];

let groupedData = R.map(R.pluck('id'), R.groupBy(R.prop('tag'),ungroupedData));

console.log({groupedData});
// groupedData:
// {
//   "foo": [99, 14, 49],
//   "bar": [33, 26, 13],
//   "baz": [99],
//   "qux": [33]
// }

let nestedTargetObjectToMerge = {
    "foo": { 
        //...
        "ids": [344, 121],
        //...
     },
     "bar": {
        //...
        "ids": [103, 66],
        //...
     }
}

// a view of the target object using a lens which matches groupedData
let view = R.map(R.view(R.lensProp("ids")), nestedTargetObjectToMerge);

console.log({view});
// view:
// {
//   "foo": [344, 121],
//   "bar": [103, 66]
// }

/* 
   let merged = ??
   // R.mergeDeepWithKey ?
   // R.over?
*/ 
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>

Intended result

 {
     "foo" : {
       "ids" : [344, 121, 99, 14, 49],
     },
     "bar" : {
       "ids" : [103, 66, 33, 26, 13],
     },
     "baz" : { 
       "ids": [99],
     },
     "qux" : {
       "ids" : [33],
     }
 }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

After you group, map the groups, and use R.applySpec with R.pluck to create an object with ids. Now you can use R.mergeDeepWith with R.concat combine the ids on both objects:

const { pipe, groupBy, prop, map, applySpec, pluck, mergeDeepWith, concat } = R;

const groupData = pipe(
  groupBy(prop('tag')),
  map(applySpec({
    ids: pluck('id')
  }))
)

const ungroupedData = [{"tag":"foo","id":99},{"tag":"bar","id":33},{"tag":"foo","id":14},{"tag":"bar","id":26},{"tag":"baz","id":99},{"tag":"qux","id":33},{"tag":"foo","id":49},{"tag":"bar","id":13}];
const nestedTargetObjectToMerge = {"foo":{"ids":[344,121]},"bar":{"ids":[103,66]}};

const groupedData = groupData(ungroupedData);

const result = mergeDeepWith(
  concat,
  nestedTargetObjectToMerge, 
  groupedData
);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>

about 4 years ago · Juan Pablo Isaza Relatório

0

My answer is similar to Ori Drori's, but enough different to include it as well:

const extractIds = compose (map (objOf ('ids')), map (pluck ('id')), groupBy (prop ('tag')))

const group = compose (flip (mergeDeepWith (concat)), extractIds)

const nestedTargetObjectToMerge = {foo: {ids: [344, 121]}, bar: {ids: [103, 66]}}
const ungroupedData = [{tag: "foo", id: 99}, {tag: "bar", id: 33}, {tag: "foo", id: 14}, {tag: "bar", id: 26}, {tag: "baz", id: 99}, {tag: "qux", id: 33}, {tag: "foo", id: 49}, {tag: "bar", id: 13}]

console .log (
  group (ungroupedData) (nestedTargetObjectToMerge)
)
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>
<script> const {compose, map, objOf, pluck, groupBy, prop, flip, mergeDeepWith, concat} = R </script>

Here extractIds converts your ungrouped data into the same format as your target object, and then group uses it to pass that into mergeDeepWith (concat). extreactId could easily be inlined into group, but I find it more readable like this.


However, I want to comment on this:

I'm new to Ramda and trying to restrict myself to not resorting to vanilla JS methods for tasks like this while I adjust. I'm stuck on something that feels very simple. Ramda loses clarity for me as soon as I need to chain some things together like this.

I'm one of Ramda's founders and chief maintainers. I'm a big fan. But I would be very wary of this philosophy. Ramda is a tool; it's meant to make it easier to work in a certain style. But it's not supposed to take over everything for you. It can often be used to make your code cleaner. Use it when it does. When it doesn't, don't try to squeeze it in. If this is solely a learning exercise, then sure, play around with Ramda solutions. But for your real work, don't try to force it.

And, while I'm pretty happy with the solution above -- and with Ori Drori's version -- I would not discount a plain JS solution using a single fold, like this:

const group = (xs) => (target) => 
  xs .reduce ((a, {tag, id}) => ({
    ...a, 
    [tag]: {...(a [tag] ?? {}), ids: [... (a [tag] ?.ids ?? []), id]}
  }), target)


const nestedTargetObjectToMerge = {foo: {ids: [344, 121]}, bar: {ids: [103, 66]}}
const ungroupedData = [{tag: "foo", id: 99}, {tag: "bar", id: 33}, {tag: "foo", id: 14}, {tag: "bar", id: 26}, {tag: "baz", id: 99}, {tag: "qux", id: 33}, {tag: "foo", id: 49}, {tag: "bar", id: 13}]

console .log (
  group (ungroupedData) (nestedTargetObjectToMerge)
)
.as-console-wrapper {max-height: 100% !important; top: 0}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda