JSON specific entities to JavaScript arrayHow do JavaScript closures work?Can comments be used in JSON?What is the correct JSON content type?How to insert an item into an array at a specific index (JavaScript)?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?Why does Google prepend while(1); to their JSON responses?How do I remove a particular element from an array in JavaScript?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?For-each over an array in JavaScript?

How to ask my office to remove the pride decorations without appearing anti-LGBTQ?

What is the meaning of [[:space:]] in bash?

Can I remove the doors before installing a sliding patio doors frame?

Finding the package which provides a given command

Is straight-up writing someone's opinions telling?

Why does FFmpeg choose 10+20+20 ms instead of an even 16 ms for 60 fps GIF images?

How to determine the optimal threshold to achieve the highest accuracy

Did 007 exist before James Bond?

Why isn't aluminium involved in biological processes?

What are "full piece" and "half piece" in chess?

What does it mean to fail a saving throw by 5 or more?

When does Fisher's "go get more data" approach make sense?

Alphanumeric Line and Curve Counting

Fantasy Story About A Boy And Girl That Enter A Fantasy World Pre-1994

Is it rude to refer to janitors as 'floor people'?

Credit card details stolen every 1-2 years. What am I doing wrong?

Investing 30k Euro as a student with basic financial knowledge but lack of time

Do I need a 50/60Hz notch filter for battery powered devices?

I Would Like to Add a Line to a Table Plot with Tikz

Why do candidates not quit if they no longer have a realistic chance to win in the 2020 US presidents election

Unix chat server making communication between terminals possible

What made Windows ME so crash-prone?

Why do so many pure math PhD students drop out or leave academia, compared to applied mathematics PhDs?

Manually select/unselect lines before forwarding to stdout



JSON specific entities to JavaScript array


How do JavaScript closures work?Can comments be used in JSON?What is the correct JSON content type?How to insert an item into an array at a specific index (JavaScript)?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?Why does Google prepend while(1); to their JSON responses?How do I remove a particular element from an array in JavaScript?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?For-each over an array in JavaScript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I have a JSON dataset coming from server side like :



[
"id":1, "year":"2001", "magnitude":20,
"id":2, "year":"2020", "magnitude":21,
"id":3, "year":"2040", "magnitude":22
]


I want to convert these data-sets as JavaScript arrays. For example, for year and magnitude in the json. I want these data in Javascript as:



var year = [2001, 2020, 2040];
var magnitude = [20, 21, 22];


I have tried different solutions but getting undefined while I alert to test data. How should I approach to solve this problem?










share|improve this question
























  • Show your code which got undefined, please.

    – Simon.Lay
    Mar 26 at 8:20

















2















I have a JSON dataset coming from server side like :



[
"id":1, "year":"2001", "magnitude":20,
"id":2, "year":"2020", "magnitude":21,
"id":3, "year":"2040", "magnitude":22
]


I want to convert these data-sets as JavaScript arrays. For example, for year and magnitude in the json. I want these data in Javascript as:



var year = [2001, 2020, 2040];
var magnitude = [20, 21, 22];


I have tried different solutions but getting undefined while I alert to test data. How should I approach to solve this problem?










share|improve this question
























  • Show your code which got undefined, please.

    – Simon.Lay
    Mar 26 at 8:20













2












2








2








I have a JSON dataset coming from server side like :



[
"id":1, "year":"2001", "magnitude":20,
"id":2, "year":"2020", "magnitude":21,
"id":3, "year":"2040", "magnitude":22
]


I want to convert these data-sets as JavaScript arrays. For example, for year and magnitude in the json. I want these data in Javascript as:



var year = [2001, 2020, 2040];
var magnitude = [20, 21, 22];


I have tried different solutions but getting undefined while I alert to test data. How should I approach to solve this problem?










share|improve this question
















I have a JSON dataset coming from server side like :



[
"id":1, "year":"2001", "magnitude":20,
"id":2, "year":"2020", "magnitude":21,
"id":3, "year":"2040", "magnitude":22
]


I want to convert these data-sets as JavaScript arrays. For example, for year and magnitude in the json. I want these data in Javascript as:



var year = [2001, 2020, 2040];
var magnitude = [20, 21, 22];


I have tried different solutions but getting undefined while I alert to test data. How should I approach to solve this problem?







javascript jquery json






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 8:24









Ibrahim Khan

18.8k7 gold badges27 silver badges45 bronze badges




18.8k7 gold badges27 silver badges45 bronze badges










asked Mar 26 at 8:16









Shunjid Rahman ShowrovShunjid Rahman Showrov

361 silver badge7 bronze badges




361 silver badge7 bronze badges












  • Show your code which got undefined, please.

    – Simon.Lay
    Mar 26 at 8:20

















  • Show your code which got undefined, please.

    – Simon.Lay
    Mar 26 at 8:20
















Show your code which got undefined, please.

– Simon.Lay
Mar 26 at 8:20





Show your code which got undefined, please.

– Simon.Lay
Mar 26 at 8:20












6 Answers
6






active

oldest

votes


















3














You could take an array of the wanted keys and collect the values in an object. Later destructure the object and get the wanted arrays.






var data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ],
keys = ['year', 'magnitude'],
collection = data.reduce((r, o) =>
keys.forEach(k => r[k].push(o[k]));
return r;
, Object.assign(...keys.map(k => ( [k]: [] )))),
year, magnitude = collection;

console.log(year);
console.log(magnitude);

.as-console-wrapper max-height: 100% !important; top: 0; 








share|improve this answer






























    2














    Just write a function and use map to get a dynamic property.






    const data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ]

    const getBy = key => data.map(e => e[key])

    console.log(getBy('year'))
    console.log(getBy('magnitude'))
    console.log(getBy('id'))








    share|improve this answer
































      2














      You could use reduce and Object.entries(). Loop through the entries of each object and update the accumulator. This works for any number of properties in the inner objects:






      const input=[id:1,year:"2001",magnitude:20,id:2,year:"2020",magnitude:21,id:3,year:"2040",magnitude:22];

      let merged = input.reduce((r, a) =>
      Object.entries(a).forEach(([k, v]) =>
      r[k] = r[k] )

      return r;
      , )

      let id, year, magnitude = merged;

      console.log(id)
      console.log(year)
      console.log(magnitude)





      This is what merged looks like:




      "id": [1, 2, 3],
      "year": ["2001", "2020", "2040"],
      "magnitude": [20, 21, 22]






      share|improve this answer

























      • Clever destructuring here. Definitely an interesting answer.

        – briosheje
        Mar 26 at 8:49


















      1














      Using the map() method for arrays would be the most modern solution for this task. Basically what it does is return a new array based on the function you provide:



      var json = [
      "id":1, "year":"2001", "magnitude":20,
      "id":2, "year":"2020", "magnitude":21,
      "id":3, "year":"2040", "magnitude":22
      ];
      var year = json.map(arr => arr.year);
      var magnitude = json.map(arr => arr.magnitude);





      share|improve this answer






























        0














        Assuming that the name of the object you get from server is 'response'.



        var years = response.map(el => el.year);
        var magnitudes = response.map(el => el.magnitude);


        Here's a sample fiddle: https://jsfiddle.net/gadawag/uye8kmvf/






        share|improve this answer






























          -1














          First parse the JSON and then use the map function






          const data = '["id":1, "year":"2001", "magnitude":20,"id":2, "year":"2020", "magnitude":21,"id":3, "year":"2040", "magnitude":22]';

          const parsed = JSON.parse(data);
          const years = parsed.map(item => item.year);
          const magnitudes = parsed.map(item => item.magnitude);

          console.log('years', years);
          console.log('magnitudes', magnitudes);





          1) I noted a JSON issue in your example. There was a comma missing after the second item.

          2) If you want to parse the years to numbers you can do this:



          const years = parsed.map(item => Number.parseInt(item.year, 10));





          share|improve this answer



























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55352539%2fjson-specific-entities-to-javascript-array%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            6 Answers
            6






            active

            oldest

            votes








            6 Answers
            6






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3














            You could take an array of the wanted keys and collect the values in an object. Later destructure the object and get the wanted arrays.






            var data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ],
            keys = ['year', 'magnitude'],
            collection = data.reduce((r, o) =>
            keys.forEach(k => r[k].push(o[k]));
            return r;
            , Object.assign(...keys.map(k => ( [k]: [] )))),
            year, magnitude = collection;

            console.log(year);
            console.log(magnitude);

            .as-console-wrapper max-height: 100% !important; top: 0; 








            share|improve this answer



























              3














              You could take an array of the wanted keys and collect the values in an object. Later destructure the object and get the wanted arrays.






              var data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ],
              keys = ['year', 'magnitude'],
              collection = data.reduce((r, o) =>
              keys.forEach(k => r[k].push(o[k]));
              return r;
              , Object.assign(...keys.map(k => ( [k]: [] )))),
              year, magnitude = collection;

              console.log(year);
              console.log(magnitude);

              .as-console-wrapper max-height: 100% !important; top: 0; 








              share|improve this answer

























                3












                3








                3







                You could take an array of the wanted keys and collect the values in an object. Later destructure the object and get the wanted arrays.






                var data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ],
                keys = ['year', 'magnitude'],
                collection = data.reduce((r, o) =>
                keys.forEach(k => r[k].push(o[k]));
                return r;
                , Object.assign(...keys.map(k => ( [k]: [] )))),
                year, magnitude = collection;

                console.log(year);
                console.log(magnitude);

                .as-console-wrapper max-height: 100% !important; top: 0; 








                share|improve this answer













                You could take an array of the wanted keys and collect the values in an object. Later destructure the object and get the wanted arrays.






                var data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ],
                keys = ['year', 'magnitude'],
                collection = data.reduce((r, o) =>
                keys.forEach(k => r[k].push(o[k]));
                return r;
                , Object.assign(...keys.map(k => ( [k]: [] )))),
                year, magnitude = collection;

                console.log(year);
                console.log(magnitude);

                .as-console-wrapper max-height: 100% !important; top: 0; 








                var data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ],
                keys = ['year', 'magnitude'],
                collection = data.reduce((r, o) =>
                keys.forEach(k => r[k].push(o[k]));
                return r;
                , Object.assign(...keys.map(k => ( [k]: [] )))),
                year, magnitude = collection;

                console.log(year);
                console.log(magnitude);

                .as-console-wrapper max-height: 100% !important; top: 0; 





                var data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ],
                keys = ['year', 'magnitude'],
                collection = data.reduce((r, o) =>
                keys.forEach(k => r[k].push(o[k]));
                return r;
                , Object.assign(...keys.map(k => ( [k]: [] )))),
                year, magnitude = collection;

                console.log(year);
                console.log(magnitude);

                .as-console-wrapper max-height: 100% !important; top: 0; 






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 26 at 8:21









                Nina ScholzNina Scholz

                216k16 gold badges130 silver badges194 bronze badges




                216k16 gold badges130 silver badges194 bronze badges























                    2














                    Just write a function and use map to get a dynamic property.






                    const data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ]

                    const getBy = key => data.map(e => e[key])

                    console.log(getBy('year'))
                    console.log(getBy('magnitude'))
                    console.log(getBy('id'))








                    share|improve this answer





























                      2














                      Just write a function and use map to get a dynamic property.






                      const data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ]

                      const getBy = key => data.map(e => e[key])

                      console.log(getBy('year'))
                      console.log(getBy('magnitude'))
                      console.log(getBy('id'))








                      share|improve this answer



























                        2












                        2








                        2







                        Just write a function and use map to get a dynamic property.






                        const data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ]

                        const getBy = key => data.map(e => e[key])

                        console.log(getBy('year'))
                        console.log(getBy('magnitude'))
                        console.log(getBy('id'))








                        share|improve this answer















                        Just write a function and use map to get a dynamic property.






                        const data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ]

                        const getBy = key => data.map(e => e[key])

                        console.log(getBy('year'))
                        console.log(getBy('magnitude'))
                        console.log(getBy('id'))








                        const data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ]

                        const getBy = key => data.map(e => e[key])

                        console.log(getBy('year'))
                        console.log(getBy('magnitude'))
                        console.log(getBy('id'))





                        const data = [ id: 1, year: "2001", magnitude: 20 , id: 2, year: "2020", magnitude: 21 , id: 3, year: "2040", magnitude: 22 ]

                        const getBy = key => data.map(e => e[key])

                        console.log(getBy('year'))
                        console.log(getBy('magnitude'))
                        console.log(getBy('id'))






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Mar 26 at 8:29

























                        answered Mar 26 at 8:21









                        birdbird

                        1,2589 silver badges20 bronze badges




                        1,2589 silver badges20 bronze badges





















                            2














                            You could use reduce and Object.entries(). Loop through the entries of each object and update the accumulator. This works for any number of properties in the inner objects:






                            const input=[id:1,year:"2001",magnitude:20,id:2,year:"2020",magnitude:21,id:3,year:"2040",magnitude:22];

                            let merged = input.reduce((r, a) =>
                            Object.entries(a).forEach(([k, v]) =>
                            r[k] = r[k] )

                            return r;
                            , )

                            let id, year, magnitude = merged;

                            console.log(id)
                            console.log(year)
                            console.log(magnitude)





                            This is what merged looks like:




                            "id": [1, 2, 3],
                            "year": ["2001", "2020", "2040"],
                            "magnitude": [20, 21, 22]






                            share|improve this answer

























                            • Clever destructuring here. Definitely an interesting answer.

                              – briosheje
                              Mar 26 at 8:49















                            2














                            You could use reduce and Object.entries(). Loop through the entries of each object and update the accumulator. This works for any number of properties in the inner objects:






                            const input=[id:1,year:"2001",magnitude:20,id:2,year:"2020",magnitude:21,id:3,year:"2040",magnitude:22];

                            let merged = input.reduce((r, a) =>
                            Object.entries(a).forEach(([k, v]) =>
                            r[k] = r[k] )

                            return r;
                            , )

                            let id, year, magnitude = merged;

                            console.log(id)
                            console.log(year)
                            console.log(magnitude)





                            This is what merged looks like:




                            "id": [1, 2, 3],
                            "year": ["2001", "2020", "2040"],
                            "magnitude": [20, 21, 22]






                            share|improve this answer

























                            • Clever destructuring here. Definitely an interesting answer.

                              – briosheje
                              Mar 26 at 8:49













                            2












                            2








                            2







                            You could use reduce and Object.entries(). Loop through the entries of each object and update the accumulator. This works for any number of properties in the inner objects:






                            const input=[id:1,year:"2001",magnitude:20,id:2,year:"2020",magnitude:21,id:3,year:"2040",magnitude:22];

                            let merged = input.reduce((r, a) =>
                            Object.entries(a).forEach(([k, v]) =>
                            r[k] = r[k] )

                            return r;
                            , )

                            let id, year, magnitude = merged;

                            console.log(id)
                            console.log(year)
                            console.log(magnitude)





                            This is what merged looks like:




                            "id": [1, 2, 3],
                            "year": ["2001", "2020", "2040"],
                            "magnitude": [20, 21, 22]






                            share|improve this answer















                            You could use reduce and Object.entries(). Loop through the entries of each object and update the accumulator. This works for any number of properties in the inner objects:






                            const input=[id:1,year:"2001",magnitude:20,id:2,year:"2020",magnitude:21,id:3,year:"2040",magnitude:22];

                            let merged = input.reduce((r, a) =>
                            Object.entries(a).forEach(([k, v]) =>
                            r[k] = r[k] )

                            return r;
                            , )

                            let id, year, magnitude = merged;

                            console.log(id)
                            console.log(year)
                            console.log(magnitude)





                            This is what merged looks like:




                            "id": [1, 2, 3],
                            "year": ["2001", "2020", "2040"],
                            "magnitude": [20, 21, 22]






                            const input=[id:1,year:"2001",magnitude:20,id:2,year:"2020",magnitude:21,id:3,year:"2040",magnitude:22];

                            let merged = input.reduce((r, a) =>
                            Object.entries(a).forEach(([k, v]) =>
                            r[k] = r[k] )

                            return r;
                            , )

                            let id, year, magnitude = merged;

                            console.log(id)
                            console.log(year)
                            console.log(magnitude)





                            const input=[id:1,year:"2001",magnitude:20,id:2,year:"2020",magnitude:21,id:3,year:"2040",magnitude:22];

                            let merged = input.reduce((r, a) =>
                            Object.entries(a).forEach(([k, v]) =>
                            r[k] = r[k] )

                            return r;
                            , )

                            let id, year, magnitude = merged;

                            console.log(id)
                            console.log(year)
                            console.log(magnitude)






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Mar 26 at 8:32

























                            answered Mar 26 at 8:21









                            adigaadiga

                            17.5k6 gold badges29 silver badges48 bronze badges




                            17.5k6 gold badges29 silver badges48 bronze badges












                            • Clever destructuring here. Definitely an interesting answer.

                              – briosheje
                              Mar 26 at 8:49

















                            • Clever destructuring here. Definitely an interesting answer.

                              – briosheje
                              Mar 26 at 8:49
















                            Clever destructuring here. Definitely an interesting answer.

                            – briosheje
                            Mar 26 at 8:49





                            Clever destructuring here. Definitely an interesting answer.

                            – briosheje
                            Mar 26 at 8:49











                            1














                            Using the map() method for arrays would be the most modern solution for this task. Basically what it does is return a new array based on the function you provide:



                            var json = [
                            "id":1, "year":"2001", "magnitude":20,
                            "id":2, "year":"2020", "magnitude":21,
                            "id":3, "year":"2040", "magnitude":22
                            ];
                            var year = json.map(arr => arr.year);
                            var magnitude = json.map(arr => arr.magnitude);





                            share|improve this answer



























                              1














                              Using the map() method for arrays would be the most modern solution for this task. Basically what it does is return a new array based on the function you provide:



                              var json = [
                              "id":1, "year":"2001", "magnitude":20,
                              "id":2, "year":"2020", "magnitude":21,
                              "id":3, "year":"2040", "magnitude":22
                              ];
                              var year = json.map(arr => arr.year);
                              var magnitude = json.map(arr => arr.magnitude);





                              share|improve this answer

























                                1












                                1








                                1







                                Using the map() method for arrays would be the most modern solution for this task. Basically what it does is return a new array based on the function you provide:



                                var json = [
                                "id":1, "year":"2001", "magnitude":20,
                                "id":2, "year":"2020", "magnitude":21,
                                "id":3, "year":"2040", "magnitude":22
                                ];
                                var year = json.map(arr => arr.year);
                                var magnitude = json.map(arr => arr.magnitude);





                                share|improve this answer













                                Using the map() method for arrays would be the most modern solution for this task. Basically what it does is return a new array based on the function you provide:



                                var json = [
                                "id":1, "year":"2001", "magnitude":20,
                                "id":2, "year":"2020", "magnitude":21,
                                "id":3, "year":"2040", "magnitude":22
                                ];
                                var year = json.map(arr => arr.year);
                                var magnitude = json.map(arr => arr.magnitude);






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Mar 26 at 8:39









                                rainh2001rainh2001

                                231 silver badge6 bronze badges




                                231 silver badge6 bronze badges





















                                    0














                                    Assuming that the name of the object you get from server is 'response'.



                                    var years = response.map(el => el.year);
                                    var magnitudes = response.map(el => el.magnitude);


                                    Here's a sample fiddle: https://jsfiddle.net/gadawag/uye8kmvf/






                                    share|improve this answer



























                                      0














                                      Assuming that the name of the object you get from server is 'response'.



                                      var years = response.map(el => el.year);
                                      var magnitudes = response.map(el => el.magnitude);


                                      Here's a sample fiddle: https://jsfiddle.net/gadawag/uye8kmvf/






                                      share|improve this answer

























                                        0












                                        0








                                        0







                                        Assuming that the name of the object you get from server is 'response'.



                                        var years = response.map(el => el.year);
                                        var magnitudes = response.map(el => el.magnitude);


                                        Here's a sample fiddle: https://jsfiddle.net/gadawag/uye8kmvf/






                                        share|improve this answer













                                        Assuming that the name of the object you get from server is 'response'.



                                        var years = response.map(el => el.year);
                                        var magnitudes = response.map(el => el.magnitude);


                                        Here's a sample fiddle: https://jsfiddle.net/gadawag/uye8kmvf/







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Mar 26 at 8:21









                                        noobprogrammernoobprogrammer

                                        1799 bronze badges




                                        1799 bronze badges





















                                            -1














                                            First parse the JSON and then use the map function






                                            const data = '["id":1, "year":"2001", "magnitude":20,"id":2, "year":"2020", "magnitude":21,"id":3, "year":"2040", "magnitude":22]';

                                            const parsed = JSON.parse(data);
                                            const years = parsed.map(item => item.year);
                                            const magnitudes = parsed.map(item => item.magnitude);

                                            console.log('years', years);
                                            console.log('magnitudes', magnitudes);





                                            1) I noted a JSON issue in your example. There was a comma missing after the second item.

                                            2) If you want to parse the years to numbers you can do this:



                                            const years = parsed.map(item => Number.parseInt(item.year, 10));





                                            share|improve this answer





























                                              -1














                                              First parse the JSON and then use the map function






                                              const data = '["id":1, "year":"2001", "magnitude":20,"id":2, "year":"2020", "magnitude":21,"id":3, "year":"2040", "magnitude":22]';

                                              const parsed = JSON.parse(data);
                                              const years = parsed.map(item => item.year);
                                              const magnitudes = parsed.map(item => item.magnitude);

                                              console.log('years', years);
                                              console.log('magnitudes', magnitudes);





                                              1) I noted a JSON issue in your example. There was a comma missing after the second item.

                                              2) If you want to parse the years to numbers you can do this:



                                              const years = parsed.map(item => Number.parseInt(item.year, 10));





                                              share|improve this answer



























                                                -1












                                                -1








                                                -1







                                                First parse the JSON and then use the map function






                                                const data = '["id":1, "year":"2001", "magnitude":20,"id":2, "year":"2020", "magnitude":21,"id":3, "year":"2040", "magnitude":22]';

                                                const parsed = JSON.parse(data);
                                                const years = parsed.map(item => item.year);
                                                const magnitudes = parsed.map(item => item.magnitude);

                                                console.log('years', years);
                                                console.log('magnitudes', magnitudes);





                                                1) I noted a JSON issue in your example. There was a comma missing after the second item.

                                                2) If you want to parse the years to numbers you can do this:



                                                const years = parsed.map(item => Number.parseInt(item.year, 10));





                                                share|improve this answer















                                                First parse the JSON and then use the map function






                                                const data = '["id":1, "year":"2001", "magnitude":20,"id":2, "year":"2020", "magnitude":21,"id":3, "year":"2040", "magnitude":22]';

                                                const parsed = JSON.parse(data);
                                                const years = parsed.map(item => item.year);
                                                const magnitudes = parsed.map(item => item.magnitude);

                                                console.log('years', years);
                                                console.log('magnitudes', magnitudes);





                                                1) I noted a JSON issue in your example. There was a comma missing after the second item.

                                                2) If you want to parse the years to numbers you can do this:



                                                const years = parsed.map(item => Number.parseInt(item.year, 10));





                                                const data = '["id":1, "year":"2001", "magnitude":20,"id":2, "year":"2020", "magnitude":21,"id":3, "year":"2040", "magnitude":22]';

                                                const parsed = JSON.parse(data);
                                                const years = parsed.map(item => item.year);
                                                const magnitudes = parsed.map(item => item.magnitude);

                                                console.log('years', years);
                                                console.log('magnitudes', magnitudes);





                                                const data = '["id":1, "year":"2001", "magnitude":20,"id":2, "year":"2020", "magnitude":21,"id":3, "year":"2040", "magnitude":22]';

                                                const parsed = JSON.parse(data);
                                                const years = parsed.map(item => item.year);
                                                const magnitudes = parsed.map(item => item.magnitude);

                                                console.log('years', years);
                                                console.log('magnitudes', magnitudes);






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Mar 26 at 8:28

























                                                answered Mar 26 at 8:23









                                                PatrickPatrick

                                                991 silver badge7 bronze badges




                                                991 silver badge7 bronze badges



























                                                    draft saved

                                                    draft discarded
















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid


                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.

                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function ()
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55352539%2fjson-specific-entities-to-javascript-array%23new-answer', 'question_page');

                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                                    용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                                                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해