Script for backward-compatibility: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
Note: The JSON object is now part of most modern web browsers (IE 8 & above). See caniuse for full listing. Credit goes to: @Spudley for his comment below
Answer from JonoW on Stack OverflowScript for backward-compatibility: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
Note: The JSON object is now part of most modern web browsers (IE 8 & above). See caniuse for full listing. Credit goes to: @Spudley for his comment below
I made it that way:
if I have:
var jsonArg1 = new Object();
jsonArg1.name = 'calc this';
jsonArg1.value = 3.1415;
var jsonArg2 = new Object();
jsonArg2.name = 'calc this again';
jsonArg2.value = 2.73;
var pluginArrayArg = new Array();
pluginArrayArg.push(jsonArg1);
pluginArrayArg.push(jsonArg2);
to convert pluginArrayArg (which is pure javascript array) into JSON array:
var jsonArray = JSON.parse(JSON.stringify(pluginArrayArg))
How to convert json array to json object in javascript - Stack Overflow
Convert JSON Array to a JSON Object using Javascript - Stack Overflow
Cannot access fields from a json array object with javascript
Converting an array to a JSON object with custom key names
You can use array reduce and pass an empty object in the accumulator. Then inside the reduce callback update the accumulator array by adding key and value
let obj = [{
"Id": 1,
"Name": "One"
}, {
"Id": 2,
"Name": "Two"
}, {
"Id": 3,
"Name": "Three"
}]
let newObj = obj.reduce(function(acc, curr) {
acc[curr.Id] = curr.Name;
return acc;
}, {})
console.log(newObj)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
let arr = [{
"Id": 1,
"Name": "One"
},
{
"Id": 2,
"Name": "Two"
},
{
"Id": 3,
"Name": "Three"
}
]
let json1 = {}
for (const s of arr) {
json1[s.Id] = s.Name
}
console.log(json1)
Run code snippetEdit code snippet Hide Results Copy to answer Expand