2015-02-05 90 views
-1

我无法将elasticsearch的后续结果转换为其他形式。有没有一个快速的方法来做到这一点,或者跳转到for循环是必要的?在此先感谢:使用不同形式的Javascript对象

格式我的数据是: 这是它是如何在原始格式:

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object] 
1. 0: Object 
1. count: 986 
2. term: "virginia" 
3. __proto__: Object 
2. 1: Object 
1. count: 447 
2. term: "washington" 
3. __proto__: Object 
3. 2: Object 
1. count: 345 
2. term: "newYork" 

我需要转换为格式为:

var states= [ 
     { 
     "key": 'popular', 
     "values": [ 
      [ 'texas' , 10] , 
      [ 'washington' , 5] , 
      [ 'new york' , 20] , 
      [ 'virginia' , 40]   
     ] 
     } 
    ]; 

为了帮助显示的数据是什么样子,这个图像显示了从控制台格式: enter image description here

+0

但随着权数字,对吧?例如,“华盛顿”会有447个,而不是5个。 – 2015-02-05 15:24:42

+2

是的,你需要一个循环(为什么人们非常想避免循环?)。它不一定是现代浏览器上的“for”循环; 'Array#map'或'Array#forEach'看起来相当适用。 – 2015-02-05 15:25:27

+0

因此循环并制作您期望的数组。 – epascarello 2015-02-05 15:25:38

回答

1

看你的样本数据,这似乎是对象的数组,每一个termcount属性。 Array#map会做的伎俩它在第一位置的字词,在第二计数转换成数组:

var states= [ 
    { 
    "key": 'popular', 
    "values": data.map(function(entry) { 
     return [entry.term, entry.count]; 
    }) 
    } 
]; 

活生生的例子:

var data = [ 
 
    { 
 
    term: "virginia", 
 
    count: 986 
 
    }, 
 
    { 
 
    term: "washington", 
 
    count: 447 
 
    }, 
 
    { 
 
    term: "newYork", 
 
    count: 345 
 
    } 
 
]; 
 

 
var states= [ 
 
    { 
 
    "key": 'popular', 
 
    "values": data.map(function(entry) { 
 
     return [entry.term, entry.count]; 
 
    }) 
 
    } 
 
]; 
 

 
// Result (I'm only using JSON here as a convenient way to 
 
// display the result; the question doesn't use JSON at all) 
 
var pre = document.createElement('pre'); 
 
pre.innerHTML = JSON.stringify(states, null, 2); 
 
document.body.appendChild(pre);

+0

非常感谢! – user2816352 2015-02-05 15:50:26

+0

@ user2816352:不用担心。我应该提到:Array#map是一个ES5特性,如果你需要支持像IE8这样的老式浏览器,你需要一个polyfill(但它*是可以被填充的东西之一)。 – 2015-02-05 15:51:17