1

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}
]

4 Answers 4

2

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

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

Comments

2

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}

Comments

0

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

Comments

0

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

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.