0

I want a solution to extract object & push into an array. but can not able to extract object because

const data = [ "userData": ["{ name: 'Test 1', age: '25'}, { name: 'Test 2', age: '26'}, { name: 'Test 3', age: '27'},"] ]

Tried code,

const test = data[0]['userData'];
const converted = JSON.parse(test);

Above code doesn't work.

Expected Output:

[
  {
    name: 'Test 1',
    age: '25'
  },
  {
    name: 'Test 2',
    age: '26'
  },
  {
    name: 'Test 3',
    age: '27'
  },
]
Manoj Ghediya
  • 547
  • 1
  • 7
  • 19
  • That happens because `JSON.parse` only accepts strings, and you are passing an array of strings. You must iterate through the array of strings and parse each element individually, and then push each result to an array. – Jorge Fuentes González Nov 28 '22 at 11:48
  • Can you give me an example ? – Manoj Ghediya Nov 28 '22 at 11:50
  • Sure: https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript there is plenty of examples there. As a tip, the `map` answer should do the trick for you. I'm not going to add the exact code so you try to understand what is happening and how to overcome it, as an excercise, as it seems that you are learning and that's important ;-) – Jorge Fuentes González Nov 28 '22 at 11:53
  • data format seems to be wrong. gives an error when pasted in console Uncaught SyntaxError: Unexpected token ':' – Nishant Nov 28 '22 at 11:58
  • I know data format is wrong, but i can not change the format because data comes from the external resource. – Manoj Ghediya Nov 28 '22 at 12:01

1 Answers1

1

The problem is in the way the json is formed. Try this:

const data = [ '{"userData": [{ "name": "Test 1", "age": 25}, { "name": "Test 2", "age": 26}, { "name": "Test 3", "age": 27}]}']
console.log(JSON.parse(data[0]))
user3425506
  • 1,285
  • 1
  • 16
  • 26
Andriu1510
  • 409
  • 1
  • 6