Arpit
Arpit

Reputation: 83

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.

Upvotes: 5

Views: 14310

Answers (5)

Danish
Danish

Reputation: 496

var obj = {
  "id": 1,
  "name": "John"
};
var arr = [];
for (var o in obj) {
  var _obj = {};
  _obj[o] = obj[o];
  arr.push(_obj);
}

console.log(arr);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

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);

Upvotes: 3

Rajkumar Somasundaram
Rajkumar Somasundaram

Reputation: 1270

This will work out.

let object = {"id" : 1, "name": "John"};
let jsonArr = [];

let objectKeys = Object.keys(object)
for(i=0;i<objectKeys.length; i++) {
  jsonArr[i] = {};
  jsonArr[i][objectKeys[i]] = object[objectKeys[i]];  
}

console.log(jsonArr)

Upvotes: 0

freelancer
freelancer

Reputation: 1164

This is the example of for loop

var arr =  {"id" : 1, "name": "John"};
var newArr = [];
for(var i in arr){
  var obj={};
  obj[i] = arr[i];
  newArr.push(obj);
}
console.log(newArr);

Upvotes: 0

marvel308
marvel308

Reputation: 10458

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);

Upvotes: 5

Related Questions