1

I want to convert this json object that contain string value separated by comma to array:

[
  {id: 1,
  name: 'book',
  colors: 'red, yellow, blue'
  },
  id: 2,
  name: 'book',
  colors: 'red, yellow, blue'
  }
 ]

to:

[
  {id: 1,
  name: 'book',
  colors: ['red', 'yellow', 'blue']
  },
  id: 2,
  name: 'book',
  colors: ['red', 'yellow', 'blue']
  }
 ]

in javascript, thank you!

1

2 Answers 2

2

You can do the following,

data = [
  {'id': 1,
  'name': 'book',
  'colors': 'red, yellow, blue'
  },
  {'id': 2,
  'name': 'book',
  'colors': 'red, yellow, blue'
  }
 ];
 
 ret = data.map((item) => {
   return {...item, colors: item.colors.split(',').map(item => item.trim())};
 })

console.log(ret);

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

1 Comment

If you split by ', ' then you can remove the map and trim
1

Strings get into arrays in each object.

let arr = [
  {id: 1,
  name: 'book',
  colors: 'red, yellow, blue'
  },
  {id: 2,
  name: 'book',
  colors: 'red, yellow, blue'
  }
  ]
 
 for (let index in arr) {
   let colorsIntoArr = arr[index].colors.split(',');   
   arr[index].colors = colorsIntoArr;   
 }
 /*
 [
  {
    "id": 1,
    "name": "book",
    "colors": [
      "red",
      " yellow",
      " blue"
    ]
  },
  {
    "id": 2,
    "name": "book",
    "colors": [
      "red",
      " yellow",
      " blue"
    ]
  }
]
*/ 
 
 console.log(arr)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.