Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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"]
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!