Search code examples
javascriptjsondatatables

How to put an array of objects into an object name data for datatables


I have an array of objects as follows:

[
  {
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [
        137.89094924926758,
        36.93143814715343
      ]
    },
    "properties": {
      "@geometry": "center",
      "@id": "way/323049815",
      "id": "way/323049815",
      "landuse": "winter_sports",
      "name": "糸魚川シーサイドバレースキー場",
      "name:en": "Itoigawa Seaside Valley Ski Resort",
      "name:ja": "糸魚川シーサイドバレースキー場",
      "source": "Bing",
      "sport": "skiing",
      "website": "https://www.seasidevalley.com/",
      "wikidata": "Q11604871",
      "wikipedia": "ja:糸魚川シーサイドバレースキー場"
    },
    
    [snip]

I want to add the above array into a data object in javascript as follows.

{
    "data": [
        //my data here.
    ]
}

I have tried this;

          let mydata = {
            "data": skidata
          }

but is places back slashed a lot like this snippet;

{
    "data": "[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\"...

How do I remove the back slashes in javascript please?

This is the specific code;

            let skidata = JSON.stringify(uniqueFeatures);
    
            let mydata = {
                "data": skidata
            }
            console.log((mydata));

When I console.log skidata, there are no backslashes. When I console.log mydata, back slashes are added, I think. This is a pict of console.log(mydata)

screen shot of console for my data


Solution

  • Don't use JSON.stringify(uniqueFeatures).

    That turns your object into a string.

    Instead of doing that, just use let mydata1 = { "data": uniqueFeatures };.

    Demo:

    let uniqueFeatures = [{
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          137.89094924926758,
          36.93143814715343
        ]
      },
      "properties": {
        "@geometry": "center",
        "@id": "way/323049815",
        "id": "way/323049815",
        "landuse": "winter_sports",
        "name": "糸魚川シーサイドバレースキー場",
        "name:en": "Itoigawa Seaside Valley Ski Resort",
        "name:ja": "糸魚川シーサイドバレースキー場",
        "source": "Bing",
        "sport": "skiing",
        "website": "https://www.seasidevalley.com/",
        "wikidata": "Q11604871",
        "wikipedia": "ja:糸魚川シーサイドバレースキー場"
      }
    }];
    
    let skidata = JSON.stringify(uniqueFeatures);
    
    let mydata1 = {
      "data": uniqueFeatures
    };
    
    let mydata2 = {
      "data": skidata
    };
    
    console.log("What you get if you stringify your object:");
    console.log(mydata2);
    
    console.log("What you want, instead:");
    console.log(mydata1);
    <!doctype html>
    <html>
    
    <head>
      <meta charset="UTF-8">
      <title>Demo</title>
    </head>
    
    <body>
    
    </body>
    
    </html>

    Reference: JSON.stringify()