What will be the best way to convert json object like
{"id" : 1, "name": "John"}
to json array
[{"id" : 1},{"name": "John"}]
using javascript.
Update: I want to do it because in Sequelize I have to pass filters as Json array with operator "or" while i have that in Json.
Approach 1: First convert the JSON string to the JavaScript object using JSON. Parse() method and then take out the values of the object and push them into the array using push() method.
Convert JSON to Array Using `json. The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string. Make sure that it has a string value coming from a server or the local source.
toJSON() calls the object's toISOString() method, which returns a string representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization, which can then be deserialized using the Date() constructor or Date. parse() as the reviver of JSON.
A JSON object contains zero, one, or more key-value pairs, also called properties. The object is surrounded by curly braces {} . Every key-value pair is separated by a comma. The order of the key-value pair is irrelevant.
You can do
let obj = {"id" : 1, "name": "John"};
let result = Object.keys(obj).map(e => {
let ret = {};
ret[e] = obj[e];
return ret;
});
console.log(result);
You could map single key/value pairs.
var object = { id: 1, name: "John" },
result = Object.keys(object).map(k => ({ [k]: object[k] }));
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With