'How to add key and values to anobject by splitting a string inside the object

I have the following array:

[
  {
    “Key”: “CUST”,
    “Segment”: “A;B;C;D;E”
  }
]

I want to transform it to:

[
  {
    “Key”: “CUST”,
    “Segment 1”: “A”,
    “Segment 2”: “B”,
    “Segment 3”: “C”,
    “Segment 4”: “D”,
    “Segment 5”: “E”
  }
]

I need to dynamically create the key names based on how many ";" separated values I have in the string “Segment,” as that number can change. I know I will probably need to use Split and maybe Reduce, Map, and Extend, but I’m having a tough time figuring it out. Can someone help me with this? Thank you!



Solution 1:[1]

You can use split as you thought with forEach

object.forEach(item => {
  item["Customer Security Segment"].split(";").forEach((segment, idx) => {
    item[`Customer Security Segment ${idx + 1}`] = segment;
  });
  delete item["Customer Security Segment"]
});

Solution 2:[2]

Thank you all for your possible solutions! I was actually able to achieve what I was looking to do using the following code:

$.extend($[‘Customer Security Segment’].split(";").reduce((accum, curVal, index) => accum.extend({["Customer Security Segment " + (index + 1)]: curVal }), {}))

This would give me the new columns I was looking for. After that I could simply drop the orignal column for "Customer Security Segment.

Solution 3:[3]

You can achieve this by using Array.map() :

// Input array
const arr = [
  {
    Key: "CUST",
    Segment: "A;B;C;D;E"
  }
];

const res = arr.map((obj) => {
  const resObj = {
    Key: obj.Key
  };
  obj.Segment.split(';').forEach((item, index) => {
    resObj['Segment ' + (index + 1)] = item
  });
    return resObj;
});

console.log(res);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Regan Karlewicz
Solution 2 quanter
Solution 3 Rohìt Jíndal