Home > Blockchain >  How to Merge Objects with same keys?
How to Merge Objects with same keys?

Time:10-30

I have JSON response coming from Node.JS API where Label values are same but other values like dd1, dd2 are different I am trying to merge same label values in one object, How could I achieve this?

   {
      "label": "Medium", 
      "dd1": "Cat A", 
      "dd2": "Non Cision",
       
  },
  {
      "label": "Medium",
      "dd1": "Cat B",
      "dd2": null,
      
  },
  {
      "label": "Tone", 
      "dd1": "Neutral", 
      "dd2": null,
      
  }

Above JSON Objects we can see Label are same in first two so, it should be merge and null values eleminated. like this

  {
      "label": "Medium", 
      "dd1": "Cat A", "Cat B" 
      "dd2": "Non Cision",
       
  }, 
  {
      "label": "Tone", 
      "dd1": "Neutral", 
      "dd2": null,
      
  }

TS Code -

var output = [];
  value.forEach(function(item) {
    var existing = output.filter(function(v, i) {
      return v.label == item.label;
    });
    if (!existing.length) {
      if (typeof item.label == "string") output.push(item);
    }
  });

  console.log(output);

CodePudding user response:

Can you check this?

const cars = [
    {
        "label": "Medium",
        "dd1": "Cat A",
        "dd2": "Non Cision",

    },
    {
        "label": "Medium",
        "dd1": "Cat B",
        "dd2": null,

    },
    {
        "label": "Tone",
        "dd1": "Neutral",
        "dd2": null,

    }
];

function groupBy(objectArray, property) {
    return objectArray.reduce(function (acc, obj) {
        let key = obj[property]
        if (!acc[key]) {
            acc[key] = []
        }
        acc[key].push(obj)
        return acc
    }, {})
}

function sum(a, c) {
    if (a && c) {
        return a   ', '   c
    } else if (a) {
        return a
    } else if (c) {
        return c
    } else {
        return null
    }
}

let object = groupBy(cars, 'label')
let arr = [];

for (const property in object) {
    arr.push({
        property,
        dd1: object[property].map(o => o.dd1).reduce((a, c) => { return sum(a, c) }),
        dd2: object[property].map(o => o.dd2).reduce((a, c) => { return sum(a, c) })
    })
}


console.log(arr);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I don't know much about Typescript - this is just a Javascript answer but I'm hoping it might be helpful.

const data = [
  { "label": "Medium", "dd1": "Cat A", "dd2": "Non Cision" },
  { "label": "Medium", "dd1": "Cat B", "dd2": null },
  { "label": "Medium", "dd1": "Cat C", "dd2": null },
  { "label": "Tone", "dd1": "Neutral", "dd2": null },
];

const merge_value = (key, current_value, new_value) =>
  (key === 'label' || !current_value) ? new_value :
    !new_value ? current_value :
      [].concat(current_value, new_value);

const merge_objects = (object1, object2) =>
  Object.entries(object2).reduce(
    (acc, [key, value]) => Object.assign(acc, { [key]: merge_value(key, object1[key], value) }),
    {}
  );

const mapped = data.reduce(
  (acc, item) => acc.set(item.label, merge_objects(acc.get(item.label) ?? {}, item)),
  new Map()
);

const res = [...mapped.values()];

console.log(res);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related