0

I have an array of strings like this. Both left and right portions in the string are separated with spaces (More than 1 space for each).

const arr = [
  'A1789   Other tuberculosis of nervous system',
  'A179    Tuberculosis of nervous system, unspecified',
  'A1801   Tuberculosis of spine'
];

I need to turn this into an array of objects like this, with the first portion as the key and the second portion as the value of the key.

const arrOfObj = [
  { A1789: 'Other tuberculosis of nervous system' },
  { A179: 'Tuberculosis of nervous system, unspecified' },
  { A1801: 'Tuberculosis of spine' }
];
2
  • Welcome to SO. Please review the "how to ask a good question" guide, specially the section about posting your code (also called a minimum, reproducible example) Commented Feb 23, 2022 at 18:02
  • I think you should take example on something like this stackoverflow.com/questions/18346710/… Commented Feb 23, 2022 at 18:07

2 Answers 2

1

I would split by space, assuming your key cannot contain space. So we'll have first item your key and the "rest" your value, which we can trim

arr.map(s => {
  const [key, ...value] = s.split(" ");
  return { [key]: value.join(" ").trim() }
})
Sign up to request clarification or add additional context in comments.

Comments

0

I'd think something like this would work:

const arrOfObj = {};
arr.forEach(item => {
    const match = str.match(/^([A-Za-z0-9]+)\s+(.+)/);
    arrOfObj[match[1]] = match[2];
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.