bruno salapic
bruno salapic

Reputation: 65

turning an array into an array with objects

I have been trying to figure out how to turn an array into an array with objects.

for example i have a json file to start with and the json file looks sorta like this

var data=[{"tasknumber":304030,
       "date":"2012-05-05",
       "operator":"john doe"},
      {"tasknumber":23130,
       "date":"2012-07-07",
       "operator":"john doeeeeeeee"},
       {"tasknumber":233330,
       "date":"2012-08-08",
       "operator":"john doe"}]

so i applied the _.countBy function that is within the underscore.js library and i get an object like this

{"john doe":2,"john doeeeeeeee":1}

ive been trying to figure out how to turn this into an array with objects so it would look something like this but i have failed in every attempt and i dont know were to start

[{operator:"john doe",
 count: 2},
{operator: "john doeeeeeeee",
count:1}]

i have tried a few things but all i get is tragedy and everything breaks, does anyone know if there are any librarys or anything that could help with this sort of thing?

Upvotes: 1

Views: 89

Answers (3)

M. F.
M. F.

Reputation: 1744

Here is an untested underscore approach that takes your initial values as loaded from the JSON file and converts directly into your desired output format:

_.chain(input)
 .groupBy(function(entry) { return entry.operator })
 .map(function(entries, operator) { 
        return {
           operator: operator,
           count: entries.length
        }   
      })
 .value();

Upvotes: 0

manonthemat
manonthemat

Reputation: 6251

Given your initial data array, you can just run this:

var data=[{"tasknumber":304030,
"date":"2012-05-05",
"operator":"john doe"},
{"tasknumber":23130,
"date":"2012-07-07",
"operator":"john doeeeeeeee"},
{"tasknumber":233330,
"date":"2012-08-08",
"operator":"john doe"}];

Function definition

const count = data => {
  // get data in format like _.countBy
  const o = data.map(x => x.operator).reduce((acc, cur) => { acc[cur] ? acc[cur] += 1 : acc[cur] = 1; return acc; }, {});
  // transform object into array of object
  return Object.keys(o).map(operator => ({operator, count: o[operator]}));
};

Test it by producing output

console.log(count(data));

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150030

Given the object (not array) {"john doe":2,"john doeeeeeeee":1} as input you can get your desired output like this:

var input = {"john doe":2,"john doeeeeeeee":1};

var output = Object.keys(input).map(function(k) {
  return {
    operator: k,
    count: input[k]
  };
});

console.log(output);

Or with ES6 arrow function syntax:

var input = {"john doe":2,"john doeeeeeeee":1};

var output = Object.keys(input).map((k) => ({ operator: k, count: input[k] }) );

console.log(output);

(Note that Underscore probably provides an even shorter way to do this, but I'm not familiar with Underscore so I've just given a plain JS solution.)

Further reading:

Upvotes: 3

Related Questions