Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalise array of objects & key by id

I'm looking to normalise some data returned from an API. Already using underscore within the project.

var res = [{
    badge_no: 123,
    id: 1,
    name: 'bob'
  }, {
    badge_no: 456,
    id: 2,
    name: 'bill'
  }, {
    badge_no: 789,
    id: 3,
    name: 'ben'
  },
  // etc
];

I'm looking to create a data structure that looks like:

var normalisedRes = [{
  1: {
    badge_no: 123,
    id: 1,
    name: 'bob'
  }
}, {
  2: {
    badge_no: 456,
    id: 2,
    name: 'bill'
  }
}, {
  3: {
    badge_no: 789,
    id: 3,
    name: 'ben'
  }
}];

It is important that I keep the id within the obj. I believe I can accomplish this with reduce but I'm struggling.

Thanks for your help!

EDIT: This question has now been answered.

From some of the advice on here, I have decided to normalise the data to return an obj which looks like:

{ '1': {data}, '2':{data}, '3':{data} }

To do this I used reduce, as I originally thought I should:

var normalised = res.reduce((acc, person) => { acc[person.id] = person; return acc; }, {});

Thanks again for all the answers!

like image 740
ste Avatar asked Oct 18 '25 04:10

ste


2 Answers

You could use Array#map with an object and set the key with id and return the object.

var array = [{ badge_no: 123, id: 1, name: 'bob' }, { badge_no: 456, id: 2, name: 'bill' }, { badge_no: 789, id: 3, name: 'ben' }],
    result = array.map(function (a) {
        var o = {};
        o[a.id] = a;
        return o;
   });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

With ES6, you could use a computed property.

var array = [{ badge_no: 123, id: 1, name: 'bob' }, { badge_no: 456, id: 2, name: 'bill' }, { badge_no: 789, id: 3, name: 'ben' }],
    result = array.map(a => ({ [a.id]: a }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 60
Nina Scholz Avatar answered Oct 20 '25 19:10

Nina Scholz


You cant use integers as key in an object. So your example isnt possible. See this relatied issue: Javascript: Using integer as key in associative array?

like image 21
Nico Mollema Avatar answered Oct 20 '25 18:10

Nico Mollema



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!