下划线将对象转换为对象数组

时间:2022-06-02 21:13:38

My data currently looks like this:

我的数据目前看起来像这样:

{ 'Australia' : [ Array[2] ],
  'Bangladesh' : [ Array[7] ],
  etc...}

I could like to convert it to:

我想把它转换成:

[ { 'country': 'Australia',
    'count': 2 },
  { 'country' : 'Bangladesh',
    'count': 7},
  etc...
 ]

What is the easiest way to convert the data?

转换数据最简单的方法是什么?

2 个解决方案

#1


2  

Using a library like Underscore, you could map the object into the form you're trying to generate:

使用像Underscore这样的库,您可以将对象映射到您尝试生成的表单中:

_.map(_.keys(data), function(key) {
    return { 'country': key, 'count': data[key].length }
});

#2


0  

Using underscore you may use something like this

使用下划线你可以使用这样的东西

var cities = {"Australia" : ["Sydney, Perth"], "US" : ["New York", "Boston"]}
var list = [];
_.each(_.keys(cities), function(countryName){
	list.push({"country" : countryName, "count" : cities[countryName].length})
});
console.log(list)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

#1


2  

Using a library like Underscore, you could map the object into the form you're trying to generate:

使用像Underscore这样的库,您可以将对象映射到您尝试生成的表单中:

_.map(_.keys(data), function(key) {
    return { 'country': key, 'count': data[key].length }
});

#2


0  

Using underscore you may use something like this

使用下划线你可以使用这样的东西

var cities = {"Australia" : ["Sydney, Perth"], "US" : ["New York", "Boston"]}
var list = [];
_.each(_.keys(cities), function(countryName){
	list.push({"country" : countryName, "count" : cities[countryName].length})
});
console.log(list)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>