How to turn an list of object into an array of objects in javascript?












-1















I'm learning to manipulate arrays and objects in Javascript.



This is a list of Objects:



Input:



{ user_id: 1,
name: 'Alice',
created_at: 2018-11-23T20:47:39.618Z,
count: '3' }
{ user_id: 4,
name: 'Daphne',
created_at: 2018-11-19T21:47:39.618Z,
count: '3' }
{ user_id: 2,
name: 'Bob',
created_at: 2018-11-23T18:47:39.618Z,
count: '2' }
{ user_id: 5,
name: 'Evan',
created_at: 2018-11-18T19:47:39.618Z,
count: '2' }
{ user_id: 6,
name: 'Fabia',
created_at: 2018-11-22T23:47:39.618Z,
count: '2' }


Desired Output:



[ { user_id: 1,
name: 'Alice',
created_at: 2018-11-23T20:47:39.618Z,
count: '3' },
{ user_id: 4,
name: 'Daphne',
created_at: 2018-11-19T21:47:39.618Z,
count: '3' },
{ user_id: 2,
name: 'Bob',
created_at: 2018-11-23T18:47:39.618Z,
count: '2' },
{ user_id: 5,
name: 'Evan',
created_at: 2018-11-18T19:47:39.618Z,
count: '2' },
{ user_id: 6,
name: 'Fabia',
created_at: 2018-11-22T23:47:39.618Z,
count: '2' } ]


I'm new to javascript programming. been trying to solve this problem but no solution yet? Anyone, please help?










share|improve this question


















  • 1





    where is the difference? what have you tried?

    – Nina Scholz
    Nov 25 '18 at 9:50






  • 3





    Your list of objects is just "floating" in space, its not valid...

    – Nick Parsons
    Nov 25 '18 at 9:50






  • 2





    There is not such thing as a (built-in) list data type in JS. What do you mean with list?

    – trincot
    Nov 25 '18 at 9:54








  • 3





    please add the original format of the input data.

    – Nina Scholz
    Nov 25 '18 at 10:02






  • 2





    The way you have presented that query result is not valid JS. Please show whether it is an object (with properties) or an array. Also show what you mean with destructuring it (into what?). To be sure, output JSON.stringify(queryresult) and put that in your question.

    – trincot
    Nov 25 '18 at 10:34
















-1















I'm learning to manipulate arrays and objects in Javascript.



This is a list of Objects:



Input:



{ user_id: 1,
name: 'Alice',
created_at: 2018-11-23T20:47:39.618Z,
count: '3' }
{ user_id: 4,
name: 'Daphne',
created_at: 2018-11-19T21:47:39.618Z,
count: '3' }
{ user_id: 2,
name: 'Bob',
created_at: 2018-11-23T18:47:39.618Z,
count: '2' }
{ user_id: 5,
name: 'Evan',
created_at: 2018-11-18T19:47:39.618Z,
count: '2' }
{ user_id: 6,
name: 'Fabia',
created_at: 2018-11-22T23:47:39.618Z,
count: '2' }


Desired Output:



[ { user_id: 1,
name: 'Alice',
created_at: 2018-11-23T20:47:39.618Z,
count: '3' },
{ user_id: 4,
name: 'Daphne',
created_at: 2018-11-19T21:47:39.618Z,
count: '3' },
{ user_id: 2,
name: 'Bob',
created_at: 2018-11-23T18:47:39.618Z,
count: '2' },
{ user_id: 5,
name: 'Evan',
created_at: 2018-11-18T19:47:39.618Z,
count: '2' },
{ user_id: 6,
name: 'Fabia',
created_at: 2018-11-22T23:47:39.618Z,
count: '2' } ]


I'm new to javascript programming. been trying to solve this problem but no solution yet? Anyone, please help?










share|improve this question


















  • 1





    where is the difference? what have you tried?

    – Nina Scholz
    Nov 25 '18 at 9:50






  • 3





    Your list of objects is just "floating" in space, its not valid...

    – Nick Parsons
    Nov 25 '18 at 9:50






  • 2





    There is not such thing as a (built-in) list data type in JS. What do you mean with list?

    – trincot
    Nov 25 '18 at 9:54








  • 3





    please add the original format of the input data.

    – Nina Scholz
    Nov 25 '18 at 10:02






  • 2





    The way you have presented that query result is not valid JS. Please show whether it is an object (with properties) or an array. Also show what you mean with destructuring it (into what?). To be sure, output JSON.stringify(queryresult) and put that in your question.

    – trincot
    Nov 25 '18 at 10:34














-1












-1








-1








I'm learning to manipulate arrays and objects in Javascript.



This is a list of Objects:



Input:



{ user_id: 1,
name: 'Alice',
created_at: 2018-11-23T20:47:39.618Z,
count: '3' }
{ user_id: 4,
name: 'Daphne',
created_at: 2018-11-19T21:47:39.618Z,
count: '3' }
{ user_id: 2,
name: 'Bob',
created_at: 2018-11-23T18:47:39.618Z,
count: '2' }
{ user_id: 5,
name: 'Evan',
created_at: 2018-11-18T19:47:39.618Z,
count: '2' }
{ user_id: 6,
name: 'Fabia',
created_at: 2018-11-22T23:47:39.618Z,
count: '2' }


Desired Output:



[ { user_id: 1,
name: 'Alice',
created_at: 2018-11-23T20:47:39.618Z,
count: '3' },
{ user_id: 4,
name: 'Daphne',
created_at: 2018-11-19T21:47:39.618Z,
count: '3' },
{ user_id: 2,
name: 'Bob',
created_at: 2018-11-23T18:47:39.618Z,
count: '2' },
{ user_id: 5,
name: 'Evan',
created_at: 2018-11-18T19:47:39.618Z,
count: '2' },
{ user_id: 6,
name: 'Fabia',
created_at: 2018-11-22T23:47:39.618Z,
count: '2' } ]


I'm new to javascript programming. been trying to solve this problem but no solution yet? Anyone, please help?










share|improve this question














I'm learning to manipulate arrays and objects in Javascript.



This is a list of Objects:



Input:



{ user_id: 1,
name: 'Alice',
created_at: 2018-11-23T20:47:39.618Z,
count: '3' }
{ user_id: 4,
name: 'Daphne',
created_at: 2018-11-19T21:47:39.618Z,
count: '3' }
{ user_id: 2,
name: 'Bob',
created_at: 2018-11-23T18:47:39.618Z,
count: '2' }
{ user_id: 5,
name: 'Evan',
created_at: 2018-11-18T19:47:39.618Z,
count: '2' }
{ user_id: 6,
name: 'Fabia',
created_at: 2018-11-22T23:47:39.618Z,
count: '2' }


Desired Output:



[ { user_id: 1,
name: 'Alice',
created_at: 2018-11-23T20:47:39.618Z,
count: '3' },
{ user_id: 4,
name: 'Daphne',
created_at: 2018-11-19T21:47:39.618Z,
count: '3' },
{ user_id: 2,
name: 'Bob',
created_at: 2018-11-23T18:47:39.618Z,
count: '2' },
{ user_id: 5,
name: 'Evan',
created_at: 2018-11-18T19:47:39.618Z,
count: '2' },
{ user_id: 6,
name: 'Fabia',
created_at: 2018-11-22T23:47:39.618Z,
count: '2' } ]


I'm new to javascript programming. been trying to solve this problem but no solution yet? Anyone, please help?







javascript arrays object






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 25 '18 at 9:50









Akash SawantAkash Sawant

529




529








  • 1





    where is the difference? what have you tried?

    – Nina Scholz
    Nov 25 '18 at 9:50






  • 3





    Your list of objects is just "floating" in space, its not valid...

    – Nick Parsons
    Nov 25 '18 at 9:50






  • 2





    There is not such thing as a (built-in) list data type in JS. What do you mean with list?

    – trincot
    Nov 25 '18 at 9:54








  • 3





    please add the original format of the input data.

    – Nina Scholz
    Nov 25 '18 at 10:02






  • 2





    The way you have presented that query result is not valid JS. Please show whether it is an object (with properties) or an array. Also show what you mean with destructuring it (into what?). To be sure, output JSON.stringify(queryresult) and put that in your question.

    – trincot
    Nov 25 '18 at 10:34














  • 1





    where is the difference? what have you tried?

    – Nina Scholz
    Nov 25 '18 at 9:50






  • 3





    Your list of objects is just "floating" in space, its not valid...

    – Nick Parsons
    Nov 25 '18 at 9:50






  • 2





    There is not such thing as a (built-in) list data type in JS. What do you mean with list?

    – trincot
    Nov 25 '18 at 9:54








  • 3





    please add the original format of the input data.

    – Nina Scholz
    Nov 25 '18 at 10:02






  • 2





    The way you have presented that query result is not valid JS. Please show whether it is an object (with properties) or an array. Also show what you mean with destructuring it (into what?). To be sure, output JSON.stringify(queryresult) and put that in your question.

    – trincot
    Nov 25 '18 at 10:34








1




1





where is the difference? what have you tried?

– Nina Scholz
Nov 25 '18 at 9:50





where is the difference? what have you tried?

– Nina Scholz
Nov 25 '18 at 9:50




3




3





Your list of objects is just "floating" in space, its not valid...

– Nick Parsons
Nov 25 '18 at 9:50





Your list of objects is just "floating" in space, its not valid...

– Nick Parsons
Nov 25 '18 at 9:50




2




2





There is not such thing as a (built-in) list data type in JS. What do you mean with list?

– trincot
Nov 25 '18 at 9:54







There is not such thing as a (built-in) list data type in JS. What do you mean with list?

– trincot
Nov 25 '18 at 9:54






3




3





please add the original format of the input data.

– Nina Scholz
Nov 25 '18 at 10:02





please add the original format of the input data.

– Nina Scholz
Nov 25 '18 at 10:02




2




2





The way you have presented that query result is not valid JS. Please show whether it is an object (with properties) or an array. Also show what you mean with destructuring it (into what?). To be sure, output JSON.stringify(queryresult) and put that in your question.

– trincot
Nov 25 '18 at 10:34





The way you have presented that query result is not valid JS. Please show whether it is an object (with properties) or an array. Also show what you mean with destructuring it (into what?). To be sure, output JSON.stringify(queryresult) and put that in your question.

– trincot
Nov 25 '18 at 10:34












3 Answers
3






active

oldest

votes


















1














You should get it as JSON out of postgres with row_to_json(), json_agg and/or array_to_json(). See this documentation about Aggregate functions



select array_to_json(array_agg(row_to_json(t)))
from (
select id, text from words
) t


Or, your list has to be a string as it is not valid JS.



`${yourQueryData}`


If the input has to be as mentioned in the question, so a string, (let's say from a txt input or whatever) here's what we can do.



We'll add brackets around that string to get started.



Then we identify each aspect that will not be valid when we parse it to JSON data.




  1. Add commas between objects: }{ to },{

  2. Get the keys and add quotes around them: user_id: to "user_id":

  3. Replace single quotes by double quotes: 'Alice' becomes "Alice"

  4. Your timestamps must be converted to strings: 2018-11-23T20:47:39.618Z to "2018-11-23T20:47:39.618Z"


Once this is all fixed, we use JSON.parse() and there you have your JSON array of objects.



There are many ways to get there. You could split your string at several places then iterate and do the necessary tasks.



Here I'll be using regex. For the sake of clarity, each step is quite explicit, even the regexes have way more groups than necessary but I hope it makes it easier to understand as it is.



This answer is based exactly on the code you provided. But it will require some modifications if a name containes a single quote for instance.






const list = `
{ user_id: 1,
name: 'Alice',
created_at: 2018-11-23T20:47:39.618Z,
count: '3' }
{ user_id: 4,
name: 'Daphne',
created_at: 2018-11-19T21:47:39.618Z,
count: '3' }
{ user_id: 2,
name: 'Bob',
created_at: 2018-11-23T18:47:39.618Z,
count: '2' }
{ user_id: 5,
name: 'Evan',
created_at: 2018-11-18T19:47:39.618Z,
count: '2' }
{ user_id: 6,
name: 'Fabia',
created_at: 2018-11-22T23:47:39.618Z,
count: '2' }
`

// Add brackets around the list to have the string representation of an array
const array = `[${list}]` // wrap into array

// 1. Add commas between objects: `}{` to `},{`
const regex = /}[rn|r|n]?{/gm // match closing followed by opening bracket
const fixObjects = array.replace(regex, "},n{") // add comma at the end of each object

// 2. Get the keys and add quotes around them: `user_id:` to `"user_id":`
const keysReg = /^(?:[s|{]+)([w]+)(?::)/gm // get keys
const fixKeys = fixObjects.replace(keysReg, function(match, g1) { return match.replace(g1, `"${g1}"`) }); // wrap keys in quotes

// 3. Replace single quotes by double quotes: `'Alice'` becomes `"Alice"`
const quotesReg = /'(.*)'/gm // match between single quotes
const fixQuotes = fixKeys.replace(quotesReg, function(match, g1) { return `"${g1}"` })

// 4. Your timestamps must be converted to strings: `2018-11-23T20:47:39.618Z` to `"2018-11-23T20:47:39.618Z"`
const datesReg = /(d{4})-(d{2})-(d{2})T(d{2}):(d{2}):(d{2}).(d{3})Z/gm // timestamps as strings
const fixDates = fixQuotes.replace(datesReg, function(match) { return `"${match}"` } )

console.log(JSON.parse(fixDates))








share|improve this answer

































    1














    Also,



    Object.values(obj);


    where obj = your data






    share|improve this answer































      0














      Try this..



      objectsArray = Array.from( ObjectsList );





      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%2f53466347%2fhow-to-turn-an-list-of-object-into-an-array-of-objects-in-javascript%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        You should get it as JSON out of postgres with row_to_json(), json_agg and/or array_to_json(). See this documentation about Aggregate functions



        select array_to_json(array_agg(row_to_json(t)))
        from (
        select id, text from words
        ) t


        Or, your list has to be a string as it is not valid JS.



        `${yourQueryData}`


        If the input has to be as mentioned in the question, so a string, (let's say from a txt input or whatever) here's what we can do.



        We'll add brackets around that string to get started.



        Then we identify each aspect that will not be valid when we parse it to JSON data.




        1. Add commas between objects: }{ to },{

        2. Get the keys and add quotes around them: user_id: to "user_id":

        3. Replace single quotes by double quotes: 'Alice' becomes "Alice"

        4. Your timestamps must be converted to strings: 2018-11-23T20:47:39.618Z to "2018-11-23T20:47:39.618Z"


        Once this is all fixed, we use JSON.parse() and there you have your JSON array of objects.



        There are many ways to get there. You could split your string at several places then iterate and do the necessary tasks.



        Here I'll be using regex. For the sake of clarity, each step is quite explicit, even the regexes have way more groups than necessary but I hope it makes it easier to understand as it is.



        This answer is based exactly on the code you provided. But it will require some modifications if a name containes a single quote for instance.






        const list = `
        { user_id: 1,
        name: 'Alice',
        created_at: 2018-11-23T20:47:39.618Z,
        count: '3' }
        { user_id: 4,
        name: 'Daphne',
        created_at: 2018-11-19T21:47:39.618Z,
        count: '3' }
        { user_id: 2,
        name: 'Bob',
        created_at: 2018-11-23T18:47:39.618Z,
        count: '2' }
        { user_id: 5,
        name: 'Evan',
        created_at: 2018-11-18T19:47:39.618Z,
        count: '2' }
        { user_id: 6,
        name: 'Fabia',
        created_at: 2018-11-22T23:47:39.618Z,
        count: '2' }
        `

        // Add brackets around the list to have the string representation of an array
        const array = `[${list}]` // wrap into array

        // 1. Add commas between objects: `}{` to `},{`
        const regex = /}[rn|r|n]?{/gm // match closing followed by opening bracket
        const fixObjects = array.replace(regex, "},n{") // add comma at the end of each object

        // 2. Get the keys and add quotes around them: `user_id:` to `"user_id":`
        const keysReg = /^(?:[s|{]+)([w]+)(?::)/gm // get keys
        const fixKeys = fixObjects.replace(keysReg, function(match, g1) { return match.replace(g1, `"${g1}"`) }); // wrap keys in quotes

        // 3. Replace single quotes by double quotes: `'Alice'` becomes `"Alice"`
        const quotesReg = /'(.*)'/gm // match between single quotes
        const fixQuotes = fixKeys.replace(quotesReg, function(match, g1) { return `"${g1}"` })

        // 4. Your timestamps must be converted to strings: `2018-11-23T20:47:39.618Z` to `"2018-11-23T20:47:39.618Z"`
        const datesReg = /(d{4})-(d{2})-(d{2})T(d{2}):(d{2}):(d{2}).(d{3})Z/gm // timestamps as strings
        const fixDates = fixQuotes.replace(datesReg, function(match) { return `"${match}"` } )

        console.log(JSON.parse(fixDates))








        share|improve this answer






























          1














          You should get it as JSON out of postgres with row_to_json(), json_agg and/or array_to_json(). See this documentation about Aggregate functions



          select array_to_json(array_agg(row_to_json(t)))
          from (
          select id, text from words
          ) t


          Or, your list has to be a string as it is not valid JS.



          `${yourQueryData}`


          If the input has to be as mentioned in the question, so a string, (let's say from a txt input or whatever) here's what we can do.



          We'll add brackets around that string to get started.



          Then we identify each aspect that will not be valid when we parse it to JSON data.




          1. Add commas between objects: }{ to },{

          2. Get the keys and add quotes around them: user_id: to "user_id":

          3. Replace single quotes by double quotes: 'Alice' becomes "Alice"

          4. Your timestamps must be converted to strings: 2018-11-23T20:47:39.618Z to "2018-11-23T20:47:39.618Z"


          Once this is all fixed, we use JSON.parse() and there you have your JSON array of objects.



          There are many ways to get there. You could split your string at several places then iterate and do the necessary tasks.



          Here I'll be using regex. For the sake of clarity, each step is quite explicit, even the regexes have way more groups than necessary but I hope it makes it easier to understand as it is.



          This answer is based exactly on the code you provided. But it will require some modifications if a name containes a single quote for instance.






          const list = `
          { user_id: 1,
          name: 'Alice',
          created_at: 2018-11-23T20:47:39.618Z,
          count: '3' }
          { user_id: 4,
          name: 'Daphne',
          created_at: 2018-11-19T21:47:39.618Z,
          count: '3' }
          { user_id: 2,
          name: 'Bob',
          created_at: 2018-11-23T18:47:39.618Z,
          count: '2' }
          { user_id: 5,
          name: 'Evan',
          created_at: 2018-11-18T19:47:39.618Z,
          count: '2' }
          { user_id: 6,
          name: 'Fabia',
          created_at: 2018-11-22T23:47:39.618Z,
          count: '2' }
          `

          // Add brackets around the list to have the string representation of an array
          const array = `[${list}]` // wrap into array

          // 1. Add commas between objects: `}{` to `},{`
          const regex = /}[rn|r|n]?{/gm // match closing followed by opening bracket
          const fixObjects = array.replace(regex, "},n{") // add comma at the end of each object

          // 2. Get the keys and add quotes around them: `user_id:` to `"user_id":`
          const keysReg = /^(?:[s|{]+)([w]+)(?::)/gm // get keys
          const fixKeys = fixObjects.replace(keysReg, function(match, g1) { return match.replace(g1, `"${g1}"`) }); // wrap keys in quotes

          // 3. Replace single quotes by double quotes: `'Alice'` becomes `"Alice"`
          const quotesReg = /'(.*)'/gm // match between single quotes
          const fixQuotes = fixKeys.replace(quotesReg, function(match, g1) { return `"${g1}"` })

          // 4. Your timestamps must be converted to strings: `2018-11-23T20:47:39.618Z` to `"2018-11-23T20:47:39.618Z"`
          const datesReg = /(d{4})-(d{2})-(d{2})T(d{2}):(d{2}):(d{2}).(d{3})Z/gm // timestamps as strings
          const fixDates = fixQuotes.replace(datesReg, function(match) { return `"${match}"` } )

          console.log(JSON.parse(fixDates))








          share|improve this answer




























            1












            1








            1







            You should get it as JSON out of postgres with row_to_json(), json_agg and/or array_to_json(). See this documentation about Aggregate functions



            select array_to_json(array_agg(row_to_json(t)))
            from (
            select id, text from words
            ) t


            Or, your list has to be a string as it is not valid JS.



            `${yourQueryData}`


            If the input has to be as mentioned in the question, so a string, (let's say from a txt input or whatever) here's what we can do.



            We'll add brackets around that string to get started.



            Then we identify each aspect that will not be valid when we parse it to JSON data.




            1. Add commas between objects: }{ to },{

            2. Get the keys and add quotes around them: user_id: to "user_id":

            3. Replace single quotes by double quotes: 'Alice' becomes "Alice"

            4. Your timestamps must be converted to strings: 2018-11-23T20:47:39.618Z to "2018-11-23T20:47:39.618Z"


            Once this is all fixed, we use JSON.parse() and there you have your JSON array of objects.



            There are many ways to get there. You could split your string at several places then iterate and do the necessary tasks.



            Here I'll be using regex. For the sake of clarity, each step is quite explicit, even the regexes have way more groups than necessary but I hope it makes it easier to understand as it is.



            This answer is based exactly on the code you provided. But it will require some modifications if a name containes a single quote for instance.






            const list = `
            { user_id: 1,
            name: 'Alice',
            created_at: 2018-11-23T20:47:39.618Z,
            count: '3' }
            { user_id: 4,
            name: 'Daphne',
            created_at: 2018-11-19T21:47:39.618Z,
            count: '3' }
            { user_id: 2,
            name: 'Bob',
            created_at: 2018-11-23T18:47:39.618Z,
            count: '2' }
            { user_id: 5,
            name: 'Evan',
            created_at: 2018-11-18T19:47:39.618Z,
            count: '2' }
            { user_id: 6,
            name: 'Fabia',
            created_at: 2018-11-22T23:47:39.618Z,
            count: '2' }
            `

            // Add brackets around the list to have the string representation of an array
            const array = `[${list}]` // wrap into array

            // 1. Add commas between objects: `}{` to `},{`
            const regex = /}[rn|r|n]?{/gm // match closing followed by opening bracket
            const fixObjects = array.replace(regex, "},n{") // add comma at the end of each object

            // 2. Get the keys and add quotes around them: `user_id:` to `"user_id":`
            const keysReg = /^(?:[s|{]+)([w]+)(?::)/gm // get keys
            const fixKeys = fixObjects.replace(keysReg, function(match, g1) { return match.replace(g1, `"${g1}"`) }); // wrap keys in quotes

            // 3. Replace single quotes by double quotes: `'Alice'` becomes `"Alice"`
            const quotesReg = /'(.*)'/gm // match between single quotes
            const fixQuotes = fixKeys.replace(quotesReg, function(match, g1) { return `"${g1}"` })

            // 4. Your timestamps must be converted to strings: `2018-11-23T20:47:39.618Z` to `"2018-11-23T20:47:39.618Z"`
            const datesReg = /(d{4})-(d{2})-(d{2})T(d{2}):(d{2}):(d{2}).(d{3})Z/gm // timestamps as strings
            const fixDates = fixQuotes.replace(datesReg, function(match) { return `"${match}"` } )

            console.log(JSON.parse(fixDates))








            share|improve this answer















            You should get it as JSON out of postgres with row_to_json(), json_agg and/or array_to_json(). See this documentation about Aggregate functions



            select array_to_json(array_agg(row_to_json(t)))
            from (
            select id, text from words
            ) t


            Or, your list has to be a string as it is not valid JS.



            `${yourQueryData}`


            If the input has to be as mentioned in the question, so a string, (let's say from a txt input or whatever) here's what we can do.



            We'll add brackets around that string to get started.



            Then we identify each aspect that will not be valid when we parse it to JSON data.




            1. Add commas between objects: }{ to },{

            2. Get the keys and add quotes around them: user_id: to "user_id":

            3. Replace single quotes by double quotes: 'Alice' becomes "Alice"

            4. Your timestamps must be converted to strings: 2018-11-23T20:47:39.618Z to "2018-11-23T20:47:39.618Z"


            Once this is all fixed, we use JSON.parse() and there you have your JSON array of objects.



            There are many ways to get there. You could split your string at several places then iterate and do the necessary tasks.



            Here I'll be using regex. For the sake of clarity, each step is quite explicit, even the regexes have way more groups than necessary but I hope it makes it easier to understand as it is.



            This answer is based exactly on the code you provided. But it will require some modifications if a name containes a single quote for instance.






            const list = `
            { user_id: 1,
            name: 'Alice',
            created_at: 2018-11-23T20:47:39.618Z,
            count: '3' }
            { user_id: 4,
            name: 'Daphne',
            created_at: 2018-11-19T21:47:39.618Z,
            count: '3' }
            { user_id: 2,
            name: 'Bob',
            created_at: 2018-11-23T18:47:39.618Z,
            count: '2' }
            { user_id: 5,
            name: 'Evan',
            created_at: 2018-11-18T19:47:39.618Z,
            count: '2' }
            { user_id: 6,
            name: 'Fabia',
            created_at: 2018-11-22T23:47:39.618Z,
            count: '2' }
            `

            // Add brackets around the list to have the string representation of an array
            const array = `[${list}]` // wrap into array

            // 1. Add commas between objects: `}{` to `},{`
            const regex = /}[rn|r|n]?{/gm // match closing followed by opening bracket
            const fixObjects = array.replace(regex, "},n{") // add comma at the end of each object

            // 2. Get the keys and add quotes around them: `user_id:` to `"user_id":`
            const keysReg = /^(?:[s|{]+)([w]+)(?::)/gm // get keys
            const fixKeys = fixObjects.replace(keysReg, function(match, g1) { return match.replace(g1, `"${g1}"`) }); // wrap keys in quotes

            // 3. Replace single quotes by double quotes: `'Alice'` becomes `"Alice"`
            const quotesReg = /'(.*)'/gm // match between single quotes
            const fixQuotes = fixKeys.replace(quotesReg, function(match, g1) { return `"${g1}"` })

            // 4. Your timestamps must be converted to strings: `2018-11-23T20:47:39.618Z` to `"2018-11-23T20:47:39.618Z"`
            const datesReg = /(d{4})-(d{2})-(d{2})T(d{2}):(d{2}):(d{2}).(d{3})Z/gm // timestamps as strings
            const fixDates = fixQuotes.replace(datesReg, function(match) { return `"${match}"` } )

            console.log(JSON.parse(fixDates))








            const list = `
            { user_id: 1,
            name: 'Alice',
            created_at: 2018-11-23T20:47:39.618Z,
            count: '3' }
            { user_id: 4,
            name: 'Daphne',
            created_at: 2018-11-19T21:47:39.618Z,
            count: '3' }
            { user_id: 2,
            name: 'Bob',
            created_at: 2018-11-23T18:47:39.618Z,
            count: '2' }
            { user_id: 5,
            name: 'Evan',
            created_at: 2018-11-18T19:47:39.618Z,
            count: '2' }
            { user_id: 6,
            name: 'Fabia',
            created_at: 2018-11-22T23:47:39.618Z,
            count: '2' }
            `

            // Add brackets around the list to have the string representation of an array
            const array = `[${list}]` // wrap into array

            // 1. Add commas between objects: `}{` to `},{`
            const regex = /}[rn|r|n]?{/gm // match closing followed by opening bracket
            const fixObjects = array.replace(regex, "},n{") // add comma at the end of each object

            // 2. Get the keys and add quotes around them: `user_id:` to `"user_id":`
            const keysReg = /^(?:[s|{]+)([w]+)(?::)/gm // get keys
            const fixKeys = fixObjects.replace(keysReg, function(match, g1) { return match.replace(g1, `"${g1}"`) }); // wrap keys in quotes

            // 3. Replace single quotes by double quotes: `'Alice'` becomes `"Alice"`
            const quotesReg = /'(.*)'/gm // match between single quotes
            const fixQuotes = fixKeys.replace(quotesReg, function(match, g1) { return `"${g1}"` })

            // 4. Your timestamps must be converted to strings: `2018-11-23T20:47:39.618Z` to `"2018-11-23T20:47:39.618Z"`
            const datesReg = /(d{4})-(d{2})-(d{2})T(d{2}):(d{2}):(d{2}).(d{3})Z/gm // timestamps as strings
            const fixDates = fixQuotes.replace(datesReg, function(match) { return `"${match}"` } )

            console.log(JSON.parse(fixDates))





            const list = `
            { user_id: 1,
            name: 'Alice',
            created_at: 2018-11-23T20:47:39.618Z,
            count: '3' }
            { user_id: 4,
            name: 'Daphne',
            created_at: 2018-11-19T21:47:39.618Z,
            count: '3' }
            { user_id: 2,
            name: 'Bob',
            created_at: 2018-11-23T18:47:39.618Z,
            count: '2' }
            { user_id: 5,
            name: 'Evan',
            created_at: 2018-11-18T19:47:39.618Z,
            count: '2' }
            { user_id: 6,
            name: 'Fabia',
            created_at: 2018-11-22T23:47:39.618Z,
            count: '2' }
            `

            // Add brackets around the list to have the string representation of an array
            const array = `[${list}]` // wrap into array

            // 1. Add commas between objects: `}{` to `},{`
            const regex = /}[rn|r|n]?{/gm // match closing followed by opening bracket
            const fixObjects = array.replace(regex, "},n{") // add comma at the end of each object

            // 2. Get the keys and add quotes around them: `user_id:` to `"user_id":`
            const keysReg = /^(?:[s|{]+)([w]+)(?::)/gm // get keys
            const fixKeys = fixObjects.replace(keysReg, function(match, g1) { return match.replace(g1, `"${g1}"`) }); // wrap keys in quotes

            // 3. Replace single quotes by double quotes: `'Alice'` becomes `"Alice"`
            const quotesReg = /'(.*)'/gm // match between single quotes
            const fixQuotes = fixKeys.replace(quotesReg, function(match, g1) { return `"${g1}"` })

            // 4. Your timestamps must be converted to strings: `2018-11-23T20:47:39.618Z` to `"2018-11-23T20:47:39.618Z"`
            const datesReg = /(d{4})-(d{2})-(d{2})T(d{2}):(d{2}):(d{2}).(d{3})Z/gm // timestamps as strings
            const fixDates = fixQuotes.replace(datesReg, function(match) { return `"${match}"` } )

            console.log(JSON.parse(fixDates))






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 25 '18 at 13:11

























            answered Nov 25 '18 at 12:31









            Asten MiesAsten Mies

            543211




            543211

























                1














                Also,



                Object.values(obj);


                where obj = your data






                share|improve this answer




























                  1














                  Also,



                  Object.values(obj);


                  where obj = your data






                  share|improve this answer


























                    1












                    1








                    1







                    Also,



                    Object.values(obj);


                    where obj = your data






                    share|improve this answer













                    Also,



                    Object.values(obj);


                    where obj = your data







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 25 '18 at 9:55









                    oetonioetoni

                    7911822




                    7911822























                        0














                        Try this..



                        objectsArray = Array.from( ObjectsList );





                        share|improve this answer




























                          0














                          Try this..



                          objectsArray = Array.from( ObjectsList );





                          share|improve this answer


























                            0












                            0








                            0







                            Try this..



                            objectsArray = Array.from( ObjectsList );





                            share|improve this answer













                            Try this..



                            objectsArray = Array.from( ObjectsList );






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 25 '18 at 9:54









                            PretorDHPretorDH

                            214




                            214






























                                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%2f53466347%2fhow-to-turn-an-list-of-object-into-an-array-of-objects-in-javascript%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

                                Wiesbaden

                                Marschland

                                Dieringhausen