Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

javascript - How to convert string to array in react js?

I have a JSON object that I cannot handle without Uncaught SyntaxError: Unexpected token o in JSON at position 1.

So i made a string out of it var array = JSON.stringify(this.props.user);

Now that string has the format I neet to loop through it / to use map function BUT it is a string. How can I bring this string into an valid array to be able to loop through it?

What I have as JSON object (copied from Chrome, typeof(..) returns object):

0:
avatar: "/media/dog_default_l.png"
birthday: "2020-09-14"
user_settings: ["P26"]
name: "Huso"
gesellig: true
verspielt: true
__proto__: Object
1:
avatar: "/media/dog_default_l.png"
birthday: "2012-04-24"
user_settings: (2) ["A9", "B5"]
name: "Medo"
gesellig: true
verspielt: false
__proto__: Object
length: 2
__proto__: Array(0)

This object as string (copied from console.log):

[{"name":"Huso","birthday":"2020-09-14","gesellig":true,"verspielt":true,"avatar":"/media/dog_default_l.png","user_settings":["P26"]},{"name":"Medo","birthday":"2012-04-24","gesellig":true,"verspielt":false,"avatar":"/media/dog_default_l.png","user_settings":["A9","B5"]}]

What I need is an array (to be able to loop through):

users: [
        { avatar: '/media/dog_default_l.png',
          birthday: '2020-09-14',
          name: 'Huso',
          gesellig: true,
          verspielt: true,
          user_settings: [
            {settings: 'P26'},
          ],
        },
        { avatar: '/media/dog_default_l.png',
          birthday: '2012-04-24',
          name: 'Medo',
          gesellig: true,
          verspielt: false,
          user_settings: [
            {settings: 'A9'},
            {settings: 'B5'},
          ],
        },
      ],

Object.entries, Object.keys etc. on the JSON object return or {} or nothing. I don't know if there is a way of getting this object looped? I'm really stuck and hope someone has a solution that works. This question is related to How to map JSON response object with nested array to state since nobody answers there.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You already have an array of objects. typeof the variable is returning Object because Arrays are Objects.

So you can do whatever you want with the array like map, filter, etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...