-3
let obj = [
  {
    name: "Manish",
    school: "{"name":"modal","email":"gmail"}",
    id: 21,
    stats: true,
    user_id: 2,
},
{
    name: "Ramesh",
    school: "{"name":"kamla","email":"yahoo"}",
    id: 10,
    stats: true,
    user_id: 3,
}]

Hello, I want to convert school property into an object. Kindly guide me. Thank you

Shahid
  • 21
  • 5
  • use `obj.forEach` to iterate over all in your array, and `JSON.parse()` to parse the `school` string – TKoL Jan 21 '21 at 14:06
  • You tagged the question with `json`. So... Did you find something online how to convert JSON into an actual object? – Andreas Jan 21 '21 at 14:06
  • 1
    [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – Andreas Jan 21 '21 at 14:07
  • The `obj` is not valid JS. May you make sure you provide a [mcve]? – evolutionxbox Jan 21 '21 at 14:08

2 Answers2

0

What you entered wasn't valid JavaScript. When you include a quote (") in a string, you need to escape it with a slash so that it knows how to differentiate between the start and the end of the string and the quote contained in your string - like this: "string containing \"quotes\""

But assuming you meant to properly escape the JSON strings, you could try this:

let objects = [
  {
    name: "Manish",
    school: "{\"name\":\"modal\",\"email\":\"gmail\"}",
    id: 21,
    stats: true,
    user_id: 2,
  },
  {
    name: "Ramesh",
    school: "{\"name\":\"kamla\",\"email\":\"yahoo\"}",
    id: 10,
    stats: true,
    user_id: 3,
  },
];

const converted = objects.map((item) => ({
  ...item, school: JSON.parse(item.school)
}));

console.log(converted);
Ben Wainwright
  • 4,224
  • 1
  • 18
  • 36
-1

try this code ==>

JSON.parse(obj[1].school)

let obj = [
  {
    name: "Manish",
    school: '{"name":"modal","email":"gmail"}',
    id: 21,
    stats: true,
    user_id: 2,
},
{
    name: "Ramesh",
    school: '{"name":"kamla","email":"yahoo"}',
    id: 10,
    stats: true,
    user_id: 3,
}]

for (var i = 0 ; i < obj.length ; i++){

obj[i].school = JSON.parse(obj[i].school)
}
console.log(obj[0])
console.log(obj[1])
  • [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – Andreas Jan 21 '21 at 14:07
  • i want apply JSON.parse(school) only in school property. How will i achieve this in array of object? – Shahid Jan 21 '21 at 14:09
  • this code will change the school property only to an object , and you can put it in a loop to get all school properties – Mohamed Ghoneim Jan 21 '21 at 14:14