Home > Net >  split the string and convert to array of objects javascript
split the string and convert to array of objects javascript

Time:02-24

I have a string data, I need to convert to array of objects in javascript

Below the code tried

var splitarr = sample.split('|');
var result = splitarr.map(e=>{
  details: e,
  values: splitarr[e]
})


var sample =  "finance=60|IT=88|sales=50"


Expected Output

[
  {"details": "finance","tag":60},
  {"details": "IT","tag":88},
  {"details": "sales","tag":50}
]

CodePudding user response:

You need another split by =, try:

var sample =  "finance=60|IT=88|sales=50";
var splitarr = sample.split('|');

var result = splitarr.map(e=>{
  let keyVal = e.split('=');
  return { details: keyVal[0], tag:keyVal[1] }
})

console.log(result);

Also when you return object from arrow function you neeed to use brackets (), otherwise it will be considered as block of code, try:

var sample =  "finance=60|IT=88|sales=50";
var splitarr = sample.split('|');

var result1 = splitarr.map(e=>{
  details: e
})

console.log(result1);

var result2 = splitarr.map(e=>({
  details: e
}))

console.log(result2);

CodePudding user response:

Another way of transforming string to object.

const sample =  "finance=60|IT=88|sales=50";

const result = sample
  .split('|')
  .map((e) => e.split('='))
  .map(([details, tag]) => ({ details, tag }));

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

CodePudding user response:

Use regex to extract all pairs eg. "finance=60" by using string.match(regex) which will return array of pairs and then use Array.map() to map into array of objects.

const text =  "finance=60|IT=88|sales=50";
const convertToObject = (str) => {
  const list = str.match(/\w =\d /g);
  return list.map(ele => {
    const [details, tag] = ele.split("=");
    return { details, tag };
  });
}
console.log(convertToObject(text));

CodePudding user response:

Observations :

  • Instead of values property it should be tag.
  • As splitter will be a simple array of elements. This splitarr[e] will not work or not exist.

You can use String.split() method to get the details and tag value.

Working Demo :

const sample =  "finance=60|IT=88|sales=50";

const splitarr = sample.split('|');

const result = splitarr.map((e) => {
    return {
    details: e.split('=')[0],
    tag: e.split('=')[1]
  }
});

console.log(result);

  • Related