Brian Var
Brian Var

Reputation: 6227

How to convert a JSON object string to a Javascript array

I passed back a JSON object from a service and converted it to a string using JSON.stringify but the required output is not as expected as shown in the first example below:

What it looks like after stringify call on the JSON object:

[{"RID":"98798","appName":"TestApp"},{"RID":"98799","appName":"TestApp Two"}]

What it needs to look like:

["98798 TestApp","98799 TestApp Two"];

How can I convert a JSON object to a presentable javascript array?

What I've tried -

This is the complete assignment for context. Inside the success function of an Ajax GET call a JSON object is returned

           success: function (result) {
                var dataRID;
                dataRID = result;
                ridAppList = JSON.stringify(dataRID);
                alert(ridAppList);

            },

Upvotes: 1

Views: 776

Answers (4)

Mulan
Mulan

Reputation: 135415

This answer also uses Array.prototype.map but combines ES6 destructuring, arrow functions, and template literals for an especially concise procedure.

var input = [
  {"RID":"98798","appName":"TestApp"},
  {"RID":"98799","appName":"TestApp Two"}
];

var output = input.map(({RID, appName})=> `${RID} ${appName}`);

console.log(output);

// [
//   "98798 TestApp",
//   "98799 TestApp Two"
// ]

Upvotes: 1

m-a-r-c-e-l-i-n-o
m-a-r-c-e-l-i-n-o

Reputation: 2672

The answers here are valid for your example, but here's a solution for arbitrary property quantity and names.

var flatObjects = [
        {"RID":"98798","appName":"TestApp"},
        {"RID":"98799","appName":"TestApp Two"},
        {"ABB":"98799","appMode":"Test", "feature": 2}
    ].map(function (obj) {
        var values = Object.keys(obj).map(function (key) { 
    	    return obj[key]
        })
        return values.join(' ')
    })

var result = JSON.stringify(flatObjects)
console.log(result)

Edit: Code formatting.

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386868

You could use the array and build a new one with Array#map

var array = [{ "RID": "98798", "appName": "TestApp" }, { "RID": "98799", "appName": "TestApp Two" }],
    result = array.map(function (a) {
        return a.RID + ' ' + a.appName;
    });
    
console.log(result);

Upvotes: 4

Nenad Vracar
Nenad Vracar

Reputation: 122135

After you parsed JSON you can use map() like this

var string = [{"RID":"98798","appName":"TestApp"},{"RID":"98799","appName":"TestApp Two"}];

var result = string.map(function(e) {
  return e.RID += ' ' + e.appName;
});

console.log(result)

Or with ES6 you can just do this

var string = [{"RID":"98798","appName":"TestApp"},{"RID":"98799","appName":"TestApp Two"}];

var result = string.map(e => e.RID += ' ' + e.appName);
console.log(result)

Upvotes: 1

Related Questions