0

I want to split a string using a comma and need to populate an array of JSON. I have the following string data

const test='00000001,name1,00000002,name2,00000003,name3,00000004,name4';

console.log(test.split('/[\n,|]/',2));

Output : ['00000001','name1','00000002','name2','00000003','name3','00000004','name4']

But I need output like this

[{id:'00000001',name:'name1'},{id:'00000002',name:'name2'},{id:'00000003',name:'name3'},{id:'00000004',name:'name4'}]

4 Answers 4

3

You can easily achieve this result by first match the strings with /(\d)+,(\w)+/gi. It will give you an array of strings.

Then you can use the map to get the desired result.

const test = "00000001,name1,00000002,name2,00000003,name3,00000004,name4";

const regex = /(\d)+,(\w)+/gi;
const result = test.match(regex).map((str) => {
  const [id, name] = str.split(",");
  return { id, name };
});

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

you can use Map function to cast your couple key value

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map?retiredLocale=it

1 Comment

There are other methods much more suitable for the task than map, which is "semantically" not purposed to do what is needed.
0

Assuming the array is of even length, this output can be achieved by doing :

const test='00000001,name1,00000002,name2,00000003,name3,00000004,name4';
let words = test.split(",");
let output = [];
let obj = {};
for (let i = 0; i < words.length; i++) {
  if (i % 2 == 0) {
  obj = {};
  obj["id"] = words[i];
  }
  
  else {
  obj["name"] = words[i];
  output.push(obj);
  }
}
console.log(output);

Comments

0

Another way could be using a pattern with named capture groups.

For capturing digits for the id, matching the comma and capture word characters for the name:

(?<id>\d+),(?<name>\w+)

const test = '00000001,name1,00000002,name2,00000003,name3,00000004,name4';
const result = Array.from(
  test.matchAll(/(?<id>\d+),(?<name>\w+)/g),
  m => m.groups
);
console.log(result);

If you want to capture all characters for the id and name except for a comma or whitespace char you can use a negated character class [^,\s]+

(?<id>[^,\s]+),(?<name>[^,\s]+)

const test = '00000001,name1,00000002,name2,00000003,name3,00000004,name4';
const result = Array.from(
  test.matchAll(/(?<id>[^,\s]+),(?<name>[^,\s]+)/g),
  m => m.groups
);
console.log(result);

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.