1

我有一个正在读入数组的数据文件。原始数据文件创建的数组如下所示:

var originalArray = [ {vendor: 2001, bananas: 50, apples:75, oranges: 12},
                      {vendor: 2002, bananas: 25, apples:60, oranges: 82},
                      {vendor: 2003, bananas: 36, apples:41, oranges: 73},
                      {vendor: 2004, bananas: 59, apples:62, oranges: 87}];

我使用 .filter 从数组中选择了一个供应商(这工作正常),但是我需要将新数组(仅包含一个供应商代码的数组)更改为一个看起来像这样的数组。

var desiredArray = [ {fruitName: "bananas", qty: 50},
                     {fruitName: "apples", qty: 75 },
                     {fruitName: "oranges", qty: 12} ];

使用 .push 我可以获得数量,但是如何让水果名称从字段名称变为“fruitName”字段中的值?

4

5 回答 5

6

如果你有选定的供应商对象,你可以做这样的事情来创建desiredArray.

var desiredArray = [];
var selectedVendor = originalArray[2]; // this is the vendor you got via .filter

for(property in selectedVendor) {
    if(property !== 'vendor') {
        desiredArray.push({fruitName: property, qty: selectedVendor[property]});
    }
}
于 2013-03-25T16:31:13.873 回答
1

尝试这个

var vendorId = 2001;

var desiredArray = originalArray.filter( function( v ) {

    return v.vendor == vendorId ;

}).map( function( v ){

    var s = [];

    for ( var i in v ){

        if ( i == 'vendor' ) continue;

        s.push( {fruitName: i , qty: v[i] } );            
    }
    return s;

}).pop(); 

desiredArray有价值_

[ {fruitName: "bananas", qty: 50},
  {fruitName: "apples", qty: 75 },
  {fruitName: "oranges", qty: 12} ]
于 2013-03-25T16:34:45.163 回答
1
   var a = [{vendor:2001,apple :50,orange:20},{vendor:2002,apple:50, orange:10}];

   var matchedVendor = 2001;

过滤器

    var filteredArray = [];
    for (var i=0; i < a.length; i++){
    if(a[i].vendor === matchedVendor){
     filteredArray = a[i];
          break;
     }}


    var desiredArray = [];

    for(prop in filteredArray){
    if(prop !== "vendor"){
        desiredArray.push({fruitName:prop,qty:filteredArray[prop]});
    }
 }
于 2013-03-25T17:07:26.050 回答
1

使用for...in循环:

    var currentVendor;
    var desiredArray = [];

    //ok, this is only an example
    currentVendor = {vendor: 2001, bananas: 50, apples:75, oranges: 12};
    for (var prop in currentVendor) {
        if(prop!='vendor')
            desiredArray.push({fruitName: prop, qty: currentVendor[prop]});
    }
于 2013-03-25T16:38:02.517 回答
0
var fruit = {};
for (var i = 0; i < originalArray.length; i++) {
  for (var key in originalArray[i]) {
    if (key != selectedVendor)
      continue;
    if (!fruit[key])
      fruit[key] = 0;
    fruit[key] += originalArray[i][key];
  }
}
var desiredArray = [];
for (var fruitName in fruit) {
  desiredArray.push({fruit: fruitName, qty: fruit[fruitName]});
}
于 2013-03-25T16:35:21.560 回答