Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Json object to Json array of key-value pair in javascript

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.

like image 429
Arpit Avatar asked Nov 23 '17 08:11

Arpit


People also ask

How do I convert JSON file to JavaScript array?

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.

Can we convert JSON to array?

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.

What is toJSON () in JSON?

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.

How does JSON pass key-value pairs?

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.


2 Answers

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);
like image 118
marvel308 Avatar answered Oct 14 '22 18:10

marvel308


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);
like image 22
Nina Scholz Avatar answered Oct 14 '22 17:10

Nina Scholz