在javascript中将Json对象转换为键值对的Json数组

时间:2017-11-23 08:26:56

标签: javascript json

转换json对象的最佳方法是什么

<div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts ">
    <div id="eli-style-heading" class="panel-heading"><% post.user.name %></div>
    <div class="panel-body panel">
        <figure>
            <p> <% post.body %></p>
            <p>  <% post.created_at %></p>
        </figure>
        <span>
            <i style="color:red;" class="glyphicon glyphicon-remove" ng-click="deletePost(post)" ng-if="post.deletable"></i>
            <span><a href="/" data-toggle="modal" data-target="#editModal">Edit</a></span>
        </span>
    </div>
</div>

到json数组

{"id" : 1, "name": "John"} 

使用javascript。

更新: 我想这样做是因为在Sequelize中我必须将过滤器作为Json数组传递给运算符&#34;或者#34;虽然我在Json有。

5 个答案:

答案 0 :(得分:3)

你可以做到

&#13;
&#13;
let obj = {"id" : 1, "name": "John"};

let result = Object.keys(obj).map(e => {
    let ret = {};
    ret[e] = obj[e];
    return ret;
});

console.log(result);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以映射单个键/值对。

&#13;
&#13;
var object = { id: 1, name: "John" },
    result = Object.keys(object).map(k => ({ [k]: object[k] }));
    
console.log(result);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这是for循环的例子

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

答案 3 :(得分:0)

这样就可以了。

&#13;
&#13;
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)
&#13;
&#13;
&#13;

答案 4 :(得分:0)

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