最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Nov 23, 2017 at 8:52 Arpit asked Nov 23, 2017 at 8:26 ArpitArpit 831 gold badge3 silver badges7 bronze badges 9
  • Share your try please ? I can be easily done by for loop. – freelancer 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? – kevinSpaceyIsKeyserSöze Commented Nov 23, 2017 at 8:29
  • do you need a special order of the items in the array? – Nina Scholz 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. – dfsq Commented Nov 23, 2017 at 8:30
  • 1 Object.entries({"id" : 1, "name": "John"}).map(([key, value]) => ({[key]: value})) – dfsq Commented Nov 23, 2017 at 8:33
 |  Show 4 more ments

5 Answers 5

Reset to default 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);

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

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

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

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)

发布评论

评论列表(0)

  1. 暂无评论