Harsh Makadia
Harsh Makadia

Reputation: 3443

converting array of objects into different objects

I have an array of objects:

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

How can I separate this array into multiple objects shown below?

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

Upvotes: 2

Views: 79

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386816

It does it, but i do not recommend it!

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

Better solution with an object

You can first build an object with the pouch values as property and assign them later to the wanted variables.

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

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1075457

So the steps are:

  1. Find the entry you want, and

  2. Create an object for the pouch

  3. Copy the properties you want

So:

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>

Upvotes: 1

Related Questions