5

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.

9
  • Share your try please ? I can be easily done by for loop. Commented Nov 23, 2017 at 8:28
  • Converting JSON object to what. Whats your input, how should your output look like. What's your maingoal you want to achieve and whats not working? Commented Nov 23, 2017 at 8:29
  • do you need a special order of the items in the array? Commented Nov 23, 2017 at 8:30
  • I guess you don't understand that result you want to get doesn't make sense because it's irregular. You can do it maybe you need it indeed. Commented Nov 23, 2017 at 8:30
  • 1
    Object.entries({"id" : 1, "name": "John"}).map(([key, value]) => ({[key]: value})) Commented Nov 23, 2017 at 8:33

5 Answers 5

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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

Comments

0

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

Comments

0

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.