Home > Software design >  How to add key and values to anobject by splitting a string inside the object
How to add key and values to anobject by splitting a string inside the object

Time:04-22

I have the following array:

[
  {
    “Customer Super Key”: “CUST-XXX”,
    “Customer Security Segment”: “BU00123;BU00234;BU00345;BU00456;BU00567”
  }
]

I want to transform it to:

[
  {
    “Customer Super Key”: “CUST-XXX”,
    “Customer Security Segment 1”: “BU00123”,
    “Customer Security Segment 2”: “BU00234”,
    “Customer Security Segment 3”: “BU00345”,
    “Customer Security Segment 4”: “BU00456”,
    “Customer Security Segment 5”: “BU00567”
  }
]

I need to dynamically create the key names based on how many ";" separated values I have in the string “Customer Security 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!

CodePudding user response:

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"]
});

CodePudding user response:

The below may be one possible solution that does not mutate the original array and instead generates a copy.

Code Snippet

// method to transform the object/s within the array
const mySplit = arr => (
  arr.map(ob =>             // first access each object by iterating over array
    Object.fromEntries(           // transform intermediate result (below) back to object
      Object.entries(ob)          // iterate over key-value pairs of object (in array)
      .reduce(                    // use "reduce" to transform specific key-value pair/s
        (fin, [k, v]) => {        // if "key" has "Segment" and "value" as semi-colon ";"
          if (k.includes("Segment") && v.includes(";")) {
            const res = ([        // transform to get multiple key-value pairs
              ...v.split(';').map(
                (nv, idx) => ([   // use "idx 1" to suffix 1, 2, 3, etc to the "key"
                  `${k} ${idx 1}`, nv
                ])
              )
            ]);
            return ([...fin, ...res]);    // return multiple key-value pairs
          } else {                        // return original key-value pair as-is (since
            return ([...fin, [k, v]]);    // it is not "Segment")
          }
        },
        []   // initialize the "fin" (accumulator/aggregator for "reduce") to empty array
      )
    )
  )   // implicit return
);

const rd = [{
  "Customer Super Key": "CUST - XXX",
  "Customer Security Segment": "BU00123;BU00234;BU00345;BU00456;BU00567"
}];

console.log('transformed array: ', mySplit(rd));

Explanation

Inline comments added to above snippet

  • Related