将对象数组转换为不同的对象

时间:2016-01-13 13:19:21

标签: javascript arrays object

我有一个对象数组:

[{ bags:10, pouch:small, weight:100, quantity:1 },
 { bags:101, pouch:large, weight:1001, quantity:11 }]

如何将此数组分成以下所示的多个对象?

small = { bags:10,weight:100,quantity:1 } 
large = { bags:101,weight:1001,quantity:11 }

2 个答案:

答案 0 :(得分:3)

它做到了,但我不推荐它!



var data = [{ bags: 10, pouch: 'small', weight: 100, quantity: 1 }, { bags: 101, pouch: 'large', weight: 1001, quantity: 11 }],
    object = data.forEach(function (a) {
        window[a.pouch] = { bags: a.bags, weight: a.weight, quantity: a.quantity };
    });

document.write('<pre>' + JSON.stringify(small, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(large, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

使用对象更好的解决方案

您可以先使用pouch值作为属性构建一个对象,然后将它们分配给所需的变量。

&#13;
&#13;
var data = [{ bags: 10, pouch: 'small', weight: 100, quantity: 1 }, { bags: 101, pouch: 'large', weight: 1001, quantity: 11 }],
    object = data.reduce(function (r, a) {
        r[a.pouch] = { bags: a.bags, weight: a.weight, quantity: a.quantity };
        return r;
    }, {});

document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');

var small = object.small,
    large = object.large;

document.write('<pre>' + JSON.stringify(small, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(large, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 1 :(得分:1)

所以步骤是:

  1. 找到您想要的条目,

  2. 为小袋创建一个对象

  3. 复制所需的属性

  4. 所以:

    var array = [{ bags:10,pouch:"small",weight:100,quantity:1},{bags:101,pouch:"large",weight:1001,quantity:11}];
    var small = get(array, "small");
    var large = get(array, "large");
    snippet.log("small = " + JSON.stringify(small));
    snippet.log("large = " + JSON.stringify(large));
    
    function get(array, pouch) {
      // Find the entry (on newer browsers you could use Array#find, and it
      // can be shimmed; I used Array#some here)
      var found;
      array.some(function(entry) {
        if (entry.pouch == pouch) {
          found = entry;
          return true;
        }
      });
      if (found) {
        // Found it, create an object with the properties we want
        return {
          bags: found.bags,
          weight: found.weight,
          quantity: found.quantity
        };
      }
      return null;
    }
    <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>