简体   繁体   中英

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.

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} var x = 'key'; y = {x: 3} will assign the object {x: 3} , x = 'key'; y = {[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 .

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;
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM