Reputation: 6227
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 -
I tried calling first stringify which doesn't give the required format as shown above:
var ridAppList = JSON.stringify(dataRID);
I also attempted converting that stringified string to a JS array using parseJSON but I get a result like - [object Obect], [object Object]
:
var ridAppList = $.parseJSON('[' + ridAppList + ']');
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
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
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
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
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