Gabriel Costin
Gabriel Costin

Reputation: 93

Convert Object to JSON Object

I am using DataTables library and I have hard times in receiving data in a proper format so I am trying to adjust it before DataTable library tries to fetch data into table. I have an ajax call which returns an object of the following format:

data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ] 

And my desired output is: data:[ [{ "SomeKey":"SomeValue" } , { ...} ],[...] ]

I have tried JSON.stringify or eval method , but did not worked , also tried those 2 methods when return type was some sort of string but then it inserts \ before " so It does not convert to json. Any help or good tracks would be appreciated.

Upvotes: 0

Views: 929

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075765

This has nothing to do with JSON. :-)

data is apparently an array of arrays of objects, where each object has properties valled Key and Value.

If you want to create a new array of arrays of objects, where the objects have a property named by the Key value whose value is the Value value, you can do that like this:

data = data.map(a => a.map(({Key,Value}) => ({[Key]: Value})));

That uses map on the arrays (both the outer and inner ones) and destructuring to pick out the Key and Value properties from each object in the subarrays, and uses computed property names to set the property name on the new object.

In ES5 and earlier, that would look like this:

data = data.map(function(a) {
    return a.map(function(obj) {
        var newObj = {};
        newObj[obj.Key] = obj.Value;
        return newObj;
    });
});

Upvotes: 3

junvar
junvar

Reputation: 11604

You should look into Array.prototype.map (mdn)

let data = [[{Key: "SomeKey", Value: "SomeValue"}]];
let output = data.map(a => a.map(({Key, Value}) => ({[Key]: Value})));
console.log(output);

Note the [Key] syntax. To put it simply, whereas var x = 'key'; y = {x: 3} will assign the object {x: 3}, x = 'key'; y = {[x]: 3} will assign the object {key: 3}.

If you're receiving literally the string "data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]", then you may trim the first 5 characters ('data:') and then use JSON.parse.

Upvotes: 3

Related Questions