2

I'm trying to convert a json response code, but i keep getting a back a string array instead. The header fields are depending on the table I query, so I cannot hardcode these.

I get a json response like:

{
  "records": [
    [
      1,
      "page one",
      300
    ],
    [
      2,
      "page 2",
      500
    ]
  ],
  "header: [
    "page_id",
    "page_name",
    "total"
  ]
}

But i would like to convert this to

{
  [
    {
      "page_id": 1,
      "page_name": "page one",
      "total": 300
    },
    {
      "page_id": 2,
      "page_name": "page 2",
      "total": 500
    }
  ]
}

I tried to create an Array and converting this to json but it still returns a string array, instead of a json array

let array = new Array;
records.forEach((record) => {
  const parts = [];
  let i = 0;
  header.forEach((title) => {
    const part = title + ': ' + record[i];
    parts.push(part);
    i++;
  });
  array.push(JSON.parse(JSON.stringify(parts)));
});
console.log(array) // Shows a string array?

I would expect

{
  [
    {
      "page_id": 1,
      "page_name": "page one",
      "total": 300
    },
    {
      "page_id": 2,
      "page_name": "page 2",
      "total": 500
    }
  ]
}

But actual

[
  [ 'page_id: 1', 'page_name: page 1', 'total: 300'],
  [ 'page_id: 2', 'page_name: page 2', 'total: 500']
]

2 Answers 2

1

The issue with the way you are doing it, is you are creating an array and pushing the values onto it, where what you want to do is create the array and push objects onto it that contain your values...

This can be done with a small amount of code using map (documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)

results.records.map((arr)=> ({
  page_id: arr[0],
  page_name: arr[1],
  total: arr[2]
});

You can also deconstruct it like so

results.records.map(([page_id, page_name, total])=> ({
  page_id,
  page_name,
  total,
});
Sign up to request clarification or add additional context in comments.

Comments

1
/*jshint esversion: 6 */

let records = {
    "records": [
      [
        1,
        "page one",
        300
      ],
      [
        2,
        "page 2",
        500
      ]
    ],

    "header": [
      "page_id",
      "page_name",
      "total"
    ]
  }; 

  let arr1 = records.header.map(data => data + ":");
  let finalarray = new Array(10); 
   var keys = arr1; 
   var values  = records.records;  
    finalarray = [];
    values.forEach((data,index) =>{
    var objJSON = new Object({});
    for (i = 0; i < keys.length; i++) {
    objJSON[keys[i]] = data[i];
    }
    finalarray.push(objJSON);  
        });

    console.log(finalarray); 

I have stored your given data in records object and then mapped the headers with colon ":" and in second loop I have joined both arrays in json object.

Output is now:

[ { 'page_id:': 1, 'page_name:': 'page one', 'total:': 300 },
  { 'page_id:': 2, 'page_name:': 'page 2', 'total:': 500 } ]

2 Comments

Thanks a lot. Modified it a little bit, but works great! Also for different tables with different fields.
You can refactor this code to more get more efficiency.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.