2

I have an array like this:

const peopleArray = [
    {
        "id": "Antoine",
        "country": "France"
    },
    {
        "id": "Alejandro",
        "country": "Spain"
    }
]

That I would like to represent as on object like this (note that id is not a property):

{
    "Antoine": {
        "country": "France"

    },
    "Alejandro": {
        "country": "Spain"
    }
}

So far I've found I can do this (elegant!):

peopleArray.reduce( (ac, p) => ({...ac, [p.id]: p }), {} )

Which produces:

{
    "Antoine": {
        "id": "Antoine",
        "country": "France"

    },
    "Alejandro": {
        "id": "Alejandro",
        "country": "Spain"
    }
}

I'm at a loss of how to accomplish the same in a terse/elegant way such that id is omitted.

Looking for a pure javascript es2017 solution that works with Node.js version 8.11.1.

Blue
  • 22,608
  • 7
  • 62
  • 92
Ville
  • 1,182
  • 10
  • 16

2 Answers2

4

If you want to make and object with id as key and remaining object as value. You can try following using Rest Parameters

ES2017

const peopleArray = [{"id": "Antoine","country": "France"},{"id": "Alejandro","country": "Spain"}];

const result = peopleArray.reduce( (ac, o) => { 
  ac[o.id] = Object.assign({}, o); 
  delete ac[o.id].id; 
  return ac; 
}, {});
console.log(result);

ES2018 - Will be able to use Rest Parameters for objects

const peopleArray = [{"id": "Antoine","country": "France"},{"id": "Alejandro","country": "Spain"}];

const result = peopleArray.reduce( (ac, {id, ...rest}) => Object.assign(ac, {[id]: rest}), {} );
console.log(result);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
  • 1
    Object destructuring the parameter is definitely the way to go. Good answer! – Blue Oct 23 '18 at 10:30
  • @FrankerZ - Thanks mate! – Nikhil Aggarwal Oct 23 '18 at 10:32
  • 1
    @FrankerZ you are absolutely right, this is the correct solution. – Just code Oct 23 '18 at 10:36
  • @NikhilAggarwal Sorry, I submitted my comment before it was finished and you may have read it before I included a reference link. Array rest/spread was es2015 but object rest/spread is es2018. https://github.com/tc39/proposal-object-rest-spread --and-- https://node.green/#ES2018-features-object-rest-spread-properties-object-rest-properties – Ville Oct 23 '18 at 12:32
  • @Ville - My bad. Then for only 1 property you can try following `const result = peopleArray.reduce( (ac, o) => Object.assign(ac, {[o.id]: {country : o.country}}), {});` – Nikhil Aggarwal Oct 23 '18 at 13:00
  • 1
    And for more properties, `const result = peopleArray.reduce( (ac, o) => { ac[o.id] = Object.assign({}, o); delete ac[o.id].id; return ac; }, {} );` – Nikhil Aggarwal Oct 23 '18 at 13:02
0

You can do : peopleArray.reduce( (ac, p) => ({...ac, [p.id]: { country : p.country } }), {} )

lone_worrior
  • 232
  • 2
  • 15